CS157: Intro to C, Part II

Spring 2018

Type Analysis

See this page as a slide show

Type Analysis

CS157 TypeAnalysis

Dimensional Analysis

My father, a mechanical engineer, taught me that you have to make sure that the dimensions are correct in a calculation, before you worry about getting the numbers right. For example:

Let’s Try That Again

Do it again, but with only dimensions:

Getting the numbers out of the way let us focus on the units, on the dimensions.

Type Analysis

Similarly, in programming, you should perform type analysis to make sure that you got the types right.

double d;
int x;
d = 12.0/x;
What type is 12.0?double
What type is x?int
What type is 12.0/x?double
What type is d?double

Good, d and 12.0/x are the same type (or, at worst, compatible types).

Type Analysis

int *p = malloc(sizeof(int));
*p = 1;
What type is p?int *
What type is *p?int
What type is 1?int

Hooray, they match!

Type Analysis

int *q;
q = 1;
What type is q?int *
What type is 1?int

That’s no good—you can't assign an int to an int *.

Type Analysis

struct Date { int m, d, y; } info[20];
short chris = 1492;
info[10].y = chris;
What type is info?array of struct Date
What type is info[10]?struct Date
What type is info[10].y?int
What type is chris?short

They’re not the same type, but they’re compatible types (you can assign a short to an int) and that’s good enough.

Type Analysis

char name[] = "Jack Applin";
strcpy(name+5, "Smith");
What type is name?array of char, or char *
What type is name+5?char *
What type is "Smith"?array of const char, or const char *
What type is strcpy’s 1st argument?char *
What type is strcpy’s 2nd argument?const char *


Type Analysis

struct Date { int m, d, y; };
struct Date *p = malloc(sizeof(struct Date) * 9);
struct Date *q = p;
(q++)->y = 1969;
What type is q?struct Date *
What type is q++?struct Date *
What type is (q++)->y?int
What type is 1969?int


Modified: 2017-12-19T11:20

User: Guest

Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building