sidharth negi
sidharth negi

Reputation: 53

Conditional Operator 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 statement j=(i=0)?2:3; gives the answer 3 when the value define to i is zero?

Upvotes: 3

Views: 93

Answers (5)

autistic
autistic

Reputation: 15632

The result of the assignment operator (= in i=0) is the new value of the object (0). 0 is a false value, thus the 'false' branch of your condition is chosen, which is 3.

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

In C, zero is considered as false and all non-zero numbers are considered as true. This:

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

is the same as

if(i = 0)
    j = 2;
else
    j = 3;

Here, i = 0 assigns 0 to i and since 0 is considered as false, the else executes, assigning 3 to j.


Do note that = is the assignment operator and assigns its left and right operands. This is different from the conditional operator == which compares both its operands and returns 0 if false and 1 if true.


If you meant ==, then j=(i==0)?2:3; is the same as

if(i == 0)
    j = 2;
else
    j = 3;

which will assign 2 to j as i == 0 is true.


To prevent these kind of mistakes, you can use Yoda Conditions as suggested by @JackWhiteIII, i.e , reversing the condition. For example,

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

can be written as

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

Since 0 is a constant value and cannot be altered, the compiler is emit an error, preventing these kind of mistakes. Note that both 0 == i and i == 0 do the same thing and both are indeed valid.

Upvotes: 5

Sourav Badami
Sourav Badami

Reputation: 779

As in the above code snippet,

{

   int i=0;

   int j;

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

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

}

you mistyped, (i==0) with (i=0) which just assigns 0 to i and checks the result, hence you're getting the output as, the answer is 3. The new code would be like, {

   int i=0;

   int j;

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

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

}

The above corrected code snipped gives the output as, the answer is 2.

Upvotes: 1

chqrlie
chqrlie

Reputation: 144695

Because you mistyped the == operator. You are setting i to the value 0 again and testing this value, which is 0, hence false.

Write this instead:

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

Upvotes: 0

Oswald
Oswald

Reputation: 31647

i=0 is an assignment. Use i==0 for comparison.

Assignments return the new value of the variable that is being assigned to. In your case, that's 0. Evaluated as a condition, that's false.

Upvotes: 2

Related Questions