Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sizeof(!0) print 1 instead of 4?

Tags:

c++

c++11

sizeof

#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?

like image 898
msc Avatar asked Oct 06 '18 06:10

msc


2 Answers

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.

like image 110
P.W Avatar answered Oct 10 '22 08:10

P.W


!0 is a bool.

sizeof(bool) depends on implementation.

like image 25
Sid S Avatar answered Oct 10 '22 09:10

Sid S