This prints 4. Why?
I'm aware how ternary operators work but this makes it complicated.
printf("%d", 0 ? 1 ? 2 : 3 : 4 );
Also this prints d.
???
int x=0, y=1 ;
printf( "d", x ? y ? x : y : x ) ;
This prints 4. Why?
I'm aware how ternary operators work but this makes it complicated.
printf("%d", 0 ? 1 ? 2 : 3 : 4 );
Also this prints d.
???
int x=0, y=1 ;
printf( "d", x ? y ? x : y : x ) ;
For the first one, its a "Nested" terenary operator. I would put parentheses around it to make it more decodable. Consider 0 ? 1 ? 2 : 3 : 4, Lets transform this to 0 ? (1 ? 2 : 3) : (4) is 0 ? the else part executes which is 4
For the second you are missing the %d
Break it down with if..else statement
if(0){
if(1)
printf("%d\n", 2);
else
printf("%d\n", 3);
}
else
printf("%d\n", 4);
0 ? 1 ? 2 : 3 : 4
parsed as a
(0 ? (1 ? 2 : 3) : 4)
So, you got output as a 4 .
That indeed should print 4. A ternary operator works as follows:
(condition) ? expression1 : expression2
If condition evaluates to true expression1 is returned, and otherwise expression2 is returned.
In your case the structure is as follows:
0?(1?2:3):4 i.e Here 1?2:3 is expression1, 4 is the expression2 and the in place of condition we have 0. As you may know 0 in a condition evaluates to false and any non-zero value evaluates to true.
So here since the condition is false (i.e 0) expression2(4) is returned.
Ternary operators is like if else. If you add parentheses to your code, things get simpler:
0 ? (1 ? 2 : 3) : 4
Remember that in C zero means false, all non-zero means true. So above statement fails at test and returns its third part, that is 4.
printf("%d", 0 ? 1 ? 2 : 3 : 4 );
Here format specifier is "%d" so it's printing the correct value that is 4. but, in
int x=0, y=1 ;
printf( "d", x ? y ? x : y : x ) ;
here no format specifier mentioned so it's just printed the "d" and ignored other parameter.
You have multiple ternary operator in the statement
printf("%d", 0 ? 1 ? 2 : 3 : 4 );
And when ever same operator comes multiple times we used to check associativity which is from Right to Left for ternary operator i.e first solves right most ternary opeartor. Or you can see this in man 1 operator
First pick right most ternary operator 1 ? 2 : 3 which results in 2. Now 3 gone.
Now it becomes 0 ? 2 : 4 which results in 4. That's why it prints 4.
Note :- As other's said, with a right associative ternary operator, you can stack them and build an if-else expression, like this:
if(0){
if(1)
printf("%d\n", 2);
else
printf("%d\n", 3);
}
else
printf("%d\n", 4);