Conditional statement query in C
In C, zero is considered false, and all non-zero numbers are considered true. It:
j=(i=0)?2:3;
coincides with
if(i = 0)
j = 2;
else
j = 3;
Here i = 0
assigns 0 to i
, and since 0 is considered false, else executes by assigning 3 to j
.
Note that it =
is an assignment operator and assigns its left and right operands. This is in contrast to the conditional operator ==
, which compares both its operands and returns 0 if false and 1 if true.
If you mean ==
, it is the j=(i==0)?2:3;
same as
if(i == 0)
j = 2;
else
j = 3;
which assigns 2 <<24> as i == 0
true.
To prevent such errors, you can use Yoda Terms as suggested by @JackWhiteIII , i.e. canceling the condition. For example,
j=(i=0)?2:3;
can be written as
j=(0=i)?2:3;
Since 0 is constant and cannot be changed, the compiler emits an error to prevent such errors. Note that both 0 == i
and i == 0
perform the same, and both are really valid.
source to share
As in the above code snippet,
{
int i=0;
int j;
j=(i=0)?2:3;
printf("the answer is %d",j);
}
you are wrong, (i == 0) with (i = 0), which just assigns 0 i and checks the result, so you get the result as answer 3 . The new code will look like, {
int i=0;
int j;
j=(i==0)?2:3;
printf("the answer is %d",j);
}
The above corrected code abbreviates the output, the answer is 2 .
source to share