Conditional statement query in C

{

   int i=0;

   int j;

   j=(i=0)?2:3;

   printf("the answer is %d",j);

}

      

I want to know why this operator j=(i=0)?2:3;

gives an answer 3

when the defining value i

is zero?

+3


source to share


5 answers


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.

+5


source


i=0

- the task. Use i==0

for comparison.



Assignments return the new value of the variable that is being assigned. In your case, it is 0

. Evaluated as a condition, false.

+2


source


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 .

+1


source


Because you have saddened the operator ==

. You set i

to value again 0

and check that value, which is 0, hence false.

Instead, write:

j = (i == 0) ? 2 : 3;

      

0


source


The result of the assignment operator ( =

in i=0

) is the new value of the object ( 0

). 0

is a false value, therefore a "false" branch of your condition is selected, which 3

.

0


source







All Articles