Reputation: 29
If
i
is anint
variable andf
is afloat
variable, what is the type of the conditional expression(i > 0 ? i : f)
?
Consider any arbitrary value of i
because I just want to know the type of the expression. I am not getting how can we check the type of this expression because if we store the result in an int
variable, we get the output as integer and if the result is stored in a float
variable, the output is float
.
Question taken from K. N. King book.
Upvotes: 0
Views: 382
Reputation: 60
#include <stdio.h>
int main(void)
{
int i=0;
double f=1.0;
printf("%d\n",i>0?i:f);
return 0;
}
gcc version 6.3.0, compile with -Wall
warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
printf("%d\n",i>0?i:f);
so the type of (condition?int:float) is float
Upvotes: -3
Reputation: 75924
Getting inspired by Determining the type of an expression:
void test()
{
int i = 0;
float f = 0.;
int ***a = i > 0 ? i : f;
}
error: initializing 'int ***' with an expression of incompatible type 'float'
int ***a = i > 0 ? i : f; ^ ~~~~~~~~~~~~~
So the type is float
.
The printf
method suggested is unreliable as in varargs float
gets promoted to double
.
As for the reasoning there is already another answer with quotes from the standard mentioning common type so I won't repeat it here.
Upvotes: 3
Reputation: 26194
In 6.5.15 Conditional operator, paragraph 4:
If both the second and third operands have arithmetic type, 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.
And then in 6.3.1.8 Usual arithmetic conversions, paragraph 1:
Otherwise, if the corresponding real type of either operand is
float
, the other operand is converted, without change of type domain, to a type whose corresponding real type isfloat
.
Therefore, the type of the expression is float
.
Upvotes: 4