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

后端 未结 7 1415
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  不知归路
    2021-01-30 08:37

    The ternary operator is a red herring.

        printf("%zu\n", sizeof(true));
    

    prints 4 (or whatever sizeof(int) is on your platform).

    The following assumes that bool is a synonym for char or a similar type of size 1, and int is larger than char.

    The reason why sizeof(true) != sizeof(bool) and sizeof(true) == sizeof(int) is simply because true is not an expression of type bool. It's an expression of type int. It is #defined as 1 in stdbool.h.

    There are no rvalues of type bool in C at all. Every such rvalue is immediately promoted to int, even when used as an argument to sizeof. Edit: this paragraph is not true, arguments to sizeof don't get promoted to int. This doesn't affect any of the conclusions though.

提交回复
热议问题