#include <stdio.h>
int main()
{
int a=-1?2:5 + 8?4:5;
printf("%d\n",a);
return 0;
}
The output of above program is 2. But why ? Please explain
#include <stdio.h>
int main()
{
int a=-1?2:5 + 8?4:5;
printf("%d\n",a);
return 0;
}
The output of above program is 2. But why ? Please explain
Write human-readable and understandable code. (Atleast, try to...)
int a=-1?2:5 + 8?4:5;
is the same as
int a = (-1) ? 2 : ( 5 + ( 8 ? 4 : 5) );
Reference: Operator Precedence
Now, let's compare that with the ternary operator condition, as mentioned in C11
, chapter §6.5.15,
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated),
So, in your case,
The statement :
int a=-1?2:5 + 8?4:5;
or better written with parentheses :
int a = (-1) ? 2 : ( 5 + 8?4:5);
which in turn means :
if (-1)
a = 2;
else {
if (8)
a = 9; //5+4
else
a = 10; //5+5
}
Any condition different than 0
is evaluated as true
. So the condition if(-1)
is different than 0
, therefore true
. Thus, the if
block will be executed and a
will get value 2
.
Because a ? b : c
evaluates to b
if a
is non-zero, and in your code a
(-1
) is non-zero and b
is 2.
Lets look it step by step process,
int a=-1?2:5 + 8?4:5;
int a = (-1) ? 2 : ( 5 + 8?4:5);
for ternary operator (condition) ? return true: return false;
0 = False
Other than 0 = true
Hence -1 = true
int a = (true) ? 2 : ( 5 + 8?4:5);
int a = 2;
On a general note: the format:
x = a ? b : c;
Means:
if (a) // always results in true unless a = 0
x = b;
else
x = c;
Now, your statement when parenthesized:
int a = (-1) ? 2 : ( 5 + ( 8 ? 4 : 5) );
is merely a shortened if-else nested group of statements. When expanded, it looks something like:
if (-1) // since it is not zero, this is true
a = 2;
else // since the if-block is true, this is ignored by the compiler
{
if (8)
a = 5 + 4; // computes to 9
else
a = 5 + 5; // computes to 10
}
Hence, since the first if-statement is true, the compiler stores 2 in variable a
.
As an aside, you should refrain from writing code that is hard to read. Even though your statement was shorter than writing an entire if-block, reading the if-else nested block is way easier to understand than reading your statement.