Why does the sizeof operator in C gives different output in case of NOT operation?

Viewed 80

I am new to programming, and was introduced with the sizeof operator of C. Playing with it, I found the following interesting thing:

long long int a = 100;

printf("%d %d\n", sizeof(a), sizeof(!a));  // Output : 8 1

I understand sizeof(a) (in my system) is 8. But I could not understand why sizeof(!a) becomes 1.

Is it because !a becomes 0, which is stored as char?

Moreover, The following code increased my confusion even more:

long long int a = 100;
char b = 9;

printf("%d %d %d %d\n", sizeof(a), sizeof(b), sizeof(a+b), sizeof(!a+b)); // Output : 8 1 8 4

Can anyone explain me, what is happening here? Due to typecasting, char should be converted into long long int, right? If so, I understand the 8 1 8 part of the output. But why sizeof(!a+b) is 4?

According to This answer, sizeof() returns size_t, which is 4 bytes in size. But couldn't get the answer of my query from it.

1 Answers

The result of the ! operator has type int, so sizeof(!a) is the same as sizeof(int).

This is documented in section 6.5.3.3 of the C standard regarding the logical negation operator !:

The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

On most systems a int is 4 bytes in size so sizeof(int) would evaluate to 4. If you're getting 1 as the result of sizeof(!a) then you're probably using a C++ compiler where the result of ! has type bool.

Related