Sunday, December 6, 2009

sizeof operator

1) Why is sizeof operator and not function

sizeof() is a compile time operator. To calculate the size of an object, we need the type information. This type information is available only at compile time. At the end of the compilation phase, the resulting object code doesn't have (or not required to have) the type information. Of course, type information can be stored to access it at run-time, but this results in bigger object code and less performance. And most of the time, we don't need it. All the runtime environments that support run time type identification (RTTI) will retain type information even after compilation phase. But, if something can be done in compilation time itself, why do it at run time?

2) On a side note, something like this is illegal...

printf("%u\n", sizeof(main)); 

The sizeof operator shall not be applied to an expression that has function type.


char *p="GOOD";
char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p),
sizeof(*p), strlen(p));
printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4

sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array
and it is not the same as the sizeof the pointer variable. Here the sizeof(a)
where a is the character array and the size of the array is 5 because the
space necessary for the terminating NULL character should also be taken
into account.

No comments:

Post a Comment