5
#include <iostream>

int main()
{
    std::cout<<sizeof(0);
    return 0;
}

Here, sizeof(0) is 4 in C++ because 0 is an integer rvalue.

But, If I write like this:

std::cout<<sizeof(!0);

here, sizeof(!0) is 1. But, !0 means it print 1, which is also, int type.

then, Why does sizeof(!0) print 1 instead of 4? What am I miss here?

msc
  • 33,420
  • 29
  • 119
  • 214

4 Answers4

17

The logical negation operator:

! rhs

If the operand is not bool, it is converted to bool using contextual conversion to bool: it is only well-formed if the declaration bool t(arg) is well-formed, for some invented temporary t.

The result is a bool prvalue.

And sizeof (bool) which is implementation defined is 1 in your implementation.

Community
  • 1
  • 1
P.W
  • 26,289
  • 6
  • 39
  • 76
7

!0 is a bool.

sizeof(bool) depends on implementation.

Sid S
  • 6,037
  • 2
  • 18
  • 24
3

By prepending the integer value with !, you convert it to a boolean - which can be represented using a single byte.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
1

When we write 0 it is an integer, but when we write !0, it implicitly convert the integer to boolean. ! operator turns any integer into boolean, you can try by writing !1, !2....these all give size of 1 byte. if you wanna know the size of !0 as an int, you can typecast it as

sizeof(int(!0));
msc
  • 33,420
  • 29
  • 119
  • 214
Akash
  • 23
  • 3