Topics / Pointers & Memory / Q19
Why is sizeof not a function?
Short answer: sizeof is a compile-time operator, not a function. The compiler evaluates it from the type of its operand, so no code runs and the operand expression is not evaluated (except for variable-length arrays). Parentheses are required only around a type name: sizeof(int); for an expression, sizeof x is valid.
int i = 5;
size_t s = sizeof(i++); /* s = 4, and i is still 5: i++ never executes */
int arr[10];
sizeof arr; /* 40 */
sizeof arr[0]; /* 4 */
sizeof(int[10]); /* 40 */
void f(int n) { int vla[n]; sizeof vla; } /* VLA: evaluated at run time */
Facts interviewers check
- The result type is
size_t(unsigned). Mixing it with negative signed values in comparisons is a classic bug:if (-1 < sizeof(int))is false. sizeof(char)is always 1. In C,sizeof('a')issizeof(int)because a character constant is anint.sizeofon a struct includes padding.sizeofon an array parameter gives the pointer size, because the parameter is really a pointer.sizeofon a function name is invalid in standard C.- Because the result is a constant expression (except for VLAs), it can be used in
#defines, array sizes and_Static_assert, but not in#if(the preprocessor runs before types exist).
Printing it: use %zu: printf("%zu\n", sizeof arr);.
Good style: malloc(n * sizeof *p) rather than malloc(n * sizeof(struct foo)); the expression form stays correct if the type of p changes.