/* sizes.c * * Looking at some of C's innards. * * Jim M */ #include #include #include /* a "C structure", i.e. a kind of clump of data with a name */ struct structure_1 { int integer1; int* an_int_pointer; int *another_pointer; void* yet_another_pointer; }; struct structure_2 { int integer1; int integer2; int* an_int_pointer; int *another_pointer; void* yet_another_pointer; }; int main(){ printf("\n"); printf(" sizeof(int) = %lu bytes \n", sizeof(int)); printf(" sizeof(long) = %lu bytes \n", sizeof(long)); printf(" sizeof(float) = %lu bytes \n", sizeof(float)); printf(" sizeof(double) = %lu bytes \n", sizeof(double)); printf(" sizeof(char*) = %lu bytes \n", sizeof(char*)); printf("\n"); printf(" sizeof(struct structure_1) = %lu bytes \n", sizeof(struct structure_1)); printf(" sizeof(struct structure_1) = %lu bytes \n", sizeof(struct structure_1)); printf(" (Explain the last two numbers.)\n"); printf("\n"); printf(" INT_MAX, LONG_MAX = %i, %li \n", INT_MAX, LONG_MAX); printf(" FLT_DIG, FLT_EPSILON, FLT_MAX = %i, %g, %g \n", FLT_DIG, FLT_EPSILON, FLT_MAX); printf(" DBL_DIG, DBL_EPSILON, DBL_MAX = %i, %g, %g \n", DBL_DIG, DBL_EPSILON, DBL_MAX); printf("\n"); // An overflow example; see CS:APP2e pg 30. // // Doing it one way gives a compilation time warning: // line 12 : int i = 200 * 300 * 400 * 500 // $ make sizes // sizes.c: In function 'main': // sizes.c:12: warning: integer overflow in expression // // But by breaking that part, there's no warning at compile time, // and so there compiler can't catch the overflow. int i = 1; i *= 200 * 300; i *= 400 * 500; printf(" int i = 200 * 300 * 400 * 500 = %i \n", i); // That prints " int i = 200 * 300 * 400 * 500 = -884901888 " // Quick quiz: can you calculate that negative number yourself? // If not, here's where it comes from: // Since 2**32 is 0 in this "int" number system, // the way to get that negative number is to find // (200*300*400*500 - n*2**32) for the smallest // value of n that makes it less than 2**31; // that turns out to be n=3 in this case. // In other words : // int32(x) = (x % 2**32 >= 2**31) ? (x % 2**32) - 2**32 : x % 2**32 // or even better, in (say) ruby // def int32(x); (x + 2**31) % 2**32 - 2**31; end printf("\n"); return 0; }