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

4

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?

Bougie answered 6/10, 2018 at 6:30 Comment(7)
!0 is a boolArnettearney
@SidS it means, it is implicitly converted int to bool type.Bougie
@SidS But, sizeof does not evaluate the expressionBougie
@M.SChaudhari yes, it receives already the result of the evaluationLichter
@M.SChaudhari - sizeof does not evaluate the expression. It works out the size of the type that would hold the result of the expression.Loginov
Okey. Thanks to all for clear my doubt.Bougie
Also note that sizeof(int) does not have to be 4, nor does sizeof(bool) = 1. But it is enough for identification of this question.Hilar
H
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.

Humectant answered 6/10, 2018 at 6:35 Comment(2)
Note you are missing a key point which is we are using sizeof w/ an expression not a typeRomo
bool operator!(int); So bool has a size of 1.Massa
A
7

!0 is a bool.

sizeof(bool) depends on implementation.

Arnettearney answered 6/10, 2018 at 6:35 Comment(1)
Why anybody say ! is the short for operator!() is it that implicit?Massa
L
3

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

Lichter answered 6/10, 2018 at 6:36 Comment(3)
you most probably mean a single byte. If you want to get a single bit per boolean, you would need some kind of bitfield.Cogswell
<joke>@Grzegorz Piwowarek So you expect it to be $\frac{1}{8}$?</joke>Hilar
Byte :) also, int is more than 4 bits!Lichter
B
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));
Bullace answered 6/10, 2018 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.