CS157 TypeAnalysis
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:
Do it again, but with only dimensions:
Getting the numbers out of the way let us focus on the units, on the dimensions.
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).
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!
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 *
.
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.
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 * |
Perfect!
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 |
Great!