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