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

msc picture msc · Oct 30, 2017 · Viewed 12.3k times · Source

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

#include <stdio.h>
#include <stdbool.h>

int main()
{
    bool a = true;
    printf("%zu\n", sizeof(bool));  // Ok
    printf("%zu\n", sizeof(a));     // Ok
    printf("%zu\n", sizeof(a ? true : false)); // Why 4?
    return 0;
}

Output (GCC):

1
1
4 // Why 4?

But here,

printf("%zu\n", sizeof(a ? true : false)); // Why 4?

the ternary operator returns boolean type and sizeof bool type is 1 byte in C.

Then why does sizeof(a ? true : false) give an output of four bytes?

Answer

Justin picture Justin · Oct 30, 2017

It's because you have #include <stdbool.h>. That header defines macros true and false to be 1 and 0, so your statement looks like this:

printf("%zu\n", sizeof(a ? 1 : 0)); // Why 4?

sizeof(int) is 4 on your platform.