mark
mark

Reputation: 27

Why is size of 0 is shown as 4?

I understand the sizeof operator, but could not understand the background of sizeof(0) producing 4 in the following program

#include<stdio.h>

int main()
{

printf("%d \n",sizeof(0));

return 1;

}

Output: 4

Upvotes: 1

Views: 89

Answers (2)

Macfer Ann
Macfer Ann

Reputation: 149

0 is an integer and sizeof gives the memory size which is 4 bytes(int)

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

sizeof returns the size of the supplied type, not the value.

Quoting C11, chapter §6.5.3.4, (emphasis mine)

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. [...]

Now, coming to type, 0, on it's own, is an integer constant.

So, sizeof(0) is the same as sizeof(int), on your platform.

That said, sizeof produces a size_t, so you should use %zu format specifier to print that.

Upvotes: 7

Related Questions