Ternary Operators in C

Viewed 143
#include <stdio.h>
int main()
{
    int x = 1;
    short int i = 2;
    float f = 3;
    if (sizeof((x == 2) ? f : i) == sizeof(float)) 
        printf("float\n");
    else if (sizeof((x == 2) ? f : i) == sizeof(short int))
        printf("short int\n");
}

Output is "float". So i don't understand why sizeof((x==2)?f:i) always return 4. I think declaration is missing variable at (x==2)?f:i; But it always returns 4(sizeof(f)).

Can you help me! This is the first programming language I learn. I know this question very stupid but with me very hard. Thanks for spends your time:) Have a good day ;)

And the first time I try to use Stackoverflow, maybe have some mistakes. Hope you forgive me

1 Answers

A type of expression is deduced statically, at compile time.

So the type and size of (x == 2) ? f : i expression is known at compile time and will not change at runtime no matter what variable values are.

The type of result of ternary operator in this case is determined using usual arithmetic conversions (C99 6.5.15p5 and C99 6.3.1.8p1). The type of (x == 2) ? f : i is determined as float.

The whole sizeof((x == 2) ? f : i) is evaluated at compile time and is equal to sizeof(float).

You could move x == 2 out of sizeof so that it is evaluated at runtime:

if ((x == 2 ? sizeof(f) : sizeof(i)) == sizeof(float))

Also note that it may happen that sizeof(short int) == sizeof(float).

Related