Why does “sizeof(a ? true : false)” give an output of four bytes?

后端 未结 7 1402
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 07:41

I have a small piece of code about the sizeof operator with the ternary operator:

#include 
#include 

int main()
{
         


        
7条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 08:13

    Quick answer:

    • sizeof(a ? true : false) evaluates to 4 because true and false are defined in as 1 and 0 respectively, so the expression expands to sizeof(a ? 1 : 0) which is an integer expression with type int, that occupies 4 bytes on your platform. For the same reason, sizeof(true) would also evaluate to 4 on your system.

    Note however that:

    • sizeof(a ? a : a) also evaluates to 4 because the ternary operator performs the integer promotions on its second and third operands if these are integer expressions. The same of course happens for sizeof(a ? true : false) and sizeof(a ? (bool)true : (bool)false), but casting the whole expression as bool behaves as expected: sizeof((bool)(a ? true : false)) -> 1.

    • also note that comparison operators evaluate to boolean values 1 or 0, but have int type: sizeof(a == a) -> 4.

    The only operators that keep the boolean nature of a would be:

    • the comma operator: both sizeof(a, a) and sizeof(true, a) evaluate to 1 at compile time.

    • the assignment operators: both sizeof(a = a) and sizeof(a = true) have a value of 1.

    • the increment operators: sizeof(a++) -> 1

    Finally, all of the above applies to C only: C++ has different semantics regarding the bool type, boolean values true and false, comparison operators and the ternary operator: all of these sizeof() expressions evaluate to 1 in C++.

提交回复
热议问题