Home > Software design >  Why it is the type/size of the conditional operator?
Why it is the type/size of the conditional operator?

Time:12-31

#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");
    return 0;
}

can anyone please help me with this question why it is printing float and why it is giving 4 for the sizeof(x==2) and can anyone help me with the flowchart ?? how ''' sizeof((x == 2) ? f : i) == sizeof(float) ''' this code is giving true or 1 in if section ??

CodePudding user response:

The code is written to demonstrate how the type of the result of the conditional operator is determined.

If the result type depended on which of the second and third operands were selected by the first operand, then the type of (x == 2) ? f : i would be float or short int, depending on x == 2. Since, in this example, x == 2 is false, it would be short int. However, execution of the code shows this is not the case, assuming that float has four bytes and short int has two bytes, as is common in current C implementations.

In (x == 2) ? f : i, x == 2 is false (because the value of x is 1), so the result value is the value of i. However, the test sizeof((x == 2) ? f : i) == sizeof(float) yields true, showing that, even though i is selected for the result value, the result type has the size of float, not the size of short int.

The rule for determining the result type of the conditional operator is in C 2018 6.5.15 5. For arithmetic operands, it says “the result type that would be determined by the usual arithmetic conversions, were they applied to those two operands, is the type of the result.” The usual arithmetic conversions are specified in C 2018 6.3.1.8. For float and short int, they produce float. So a conditional operator with float and short int for its second and third operands has result type float.

  • Related