3

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.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
steve
  • 33
  • 2
  • 3
    The output should not be `1` , you are most likely running a C++ compiler (C++ is a different language to C). However the whole program causes undefined behaviour due to incorrect format specifier in printf, so anything can happen. – M.M Aug 28 '20 at 13:41
  • @M.M yes, it's a C++ compiler. Also, thanks to you, I came to know that `bool` is data type in C++, but it's just an alias in C. – steve Aug 28 '20 at 13:44
  • Don't mix up typecasting with conversion caused by implicit type promotion. A cast is always explicit and always done by the programmer with `(type)`. Apart from the bool vs int issue, there's implicit conversion, see https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules. – Lundin Aug 28 '20 at 14:08
  • @steve C also has a bool data type, however in C the result of the `!` operator does not have the bool data type – M.M Aug 28 '20 at 14:09

1 Answers1

6

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • `I understand sizeof(a) (in my system) is 8. But I could not understand why sizeof(!a) becomes 1.` than what is this behaviour ? – Umar Farooq Aug 28 '20 at 13:36
  • 1
    @UmarFarooq Are you using a c++ compiler? If so, the result of `!` has type `bool`. – dbush Aug 28 '20 at 13:38