-1

I don't understand how the size is equal to float and not short int as the size of i is short int.

Here is my code:

#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");
}
Son Truong
  • 13,661
  • 5
  • 32
  • 58
  • 7
    Ternary operator only has one type. In your example `short int` is promoted to `float`. – Osiris Aug 28 '18 at 13:53
  • 2
    `sizeof` isn't a function so it can't evaluate a runtime value like `x == 2` – cleblanc Aug 28 '18 at 13:55
  • 2
    @cleblanc The ternary operator has a defined type at compile time. `sizeof` is not evaluated (except for VLAs). – Osiris Aug 28 '18 at 13:58
  • 2
    @Osiris sure it does and that's why it compiles, I'm just pointing out that it won't do what she seems to want which is evaluate `x == 2` – cleblanc Aug 28 '18 at 13:59

1 Answers1

2

The type of a conditional expression is always defined at compile time. The expression (x == 2) ? f : i is of type float since i is promoted.

sizeof is not evaluated (except for VLAs), so it is not even checked if x == 2.

Osiris
  • 2,783
  • 9
  • 17