Shubham S. Naik Shubham S. Naik - 2 months ago 18
C Question

How sizeof operator works in C?

In this below code:

int main(void)
return 0;

When compiled on gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 compiler it gives warning:

format ‘%d’ expects argument of type ‘int’, but argument 2 has type
‘long unsigned int’ [-Wformat=] printf("%d",sizeof(int));

Why I am getting this warning? Is it that return type of sizeof is 'long unsigned int' ?

When I replaced '%d' with '%ld' the warning went.


The sizeof operator is processed at compile time (and can be applied on both types and expressions). It gives some constant* of type size_t. On your system (and mine Debian/Linux/x86-64 also) sizeof(int) is (size_t)4. That size_t type is often typedef-ed in some type like unsigned long (but what integral type it actually is depends upon the implementation). You could code

printf("%d", (int)sizeof(int));

or (since printf understands the %zd or %zu control format string for size_t)

printf("%zu", sizeof(int));

For maximum portability, use %zu (not %ld) for printing size_t (because you might find systems or configurations on which size_t is unsigned int etc...).

Note *: sizeof is always constant, except for VLA