Expression using ternary operator

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

If aand bare initialized to 100and 200accordingly, what are the values aand bafter the ternary operator?

The answer was a=101, b=200.

How is this possible?

+4
source share
3 answers

Just add some parentheses and spaces to make them more readable, and this should be obvious:

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

(Refer to table C to find out why the brackets can be placed where they are in the above expression.)

So this is essentially true:

a += 1;
+3
source

, . a += a==100. a += 1, == 1 = true.

+1

, :

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

C ( java javascript-):

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

b = 200, b >= 300 false, , a == 100 1 a 100. 1 a, a 101. b .

+1

Source: https://habr.com/ru/post/1679102/


All Articles