Geo
Geo

Reputation: 41

Expression using ternary operator

a+=b>=300?b=100:a==100;

If a and b are initialized to 100 and 200 respectively, what will be the values of a and b after executing the ternary operator?

The answer was a=101, b=200.

How is this possible?

Upvotes: 4

Views: 76

Answers (3)

chqrlie
chqrlie

Reputation: 144695

First add some spaces to make this statement expression easier to parse visually:

a += b >= 300 ? b = 100 : a == 100;

Then parse it according to the C grammar (which is subtly different from the java or javascript grammars in this particular case):

a +=
      (b >= 300) ?
           b = 100 :
           a == 100
      ;

Since b = 200, the test b >= 300 evaluates to false and the first branch of the ternary operator is not evaluated, but the second branch is and a == 100 evaluates to 1 as a is indeed equal to 100. The result of the ternary operator, 1, is added to a, hence the new value for a is 101. b is unchanged.

Upvotes: 1

Lundin
Lundin

Reputation: 213603

The conditional operator has nothing to do with it, basically it just adds clutter here. Your program is equivalent to a += a==100. Which gives a += 1, since the result of == is a boolean 1=true.

Upvotes: 1

Paul R
Paul R

Reputation: 212949

Just add some parentheses and spaces to make it more readable and it should be obvious:

a += ((b >= 300) ? (b = 100) : (a == 100));

(Refer to a C operator precedence table to see why the parentheses can be placed where they are in the above expression.)

So this is essentially just:

a += 1;

Upvotes: 3

Related Questions