Search code examples
c++operator-keywordternary

C++ ternary operator confusion


I have the following program, which should be simple to everyone but me!

#include <iostream>
using namespace std;
int main()
{

int a, b;
b = 1;

cout << ((a = --b) ? b : (b = -99)) << '\n' << "a is " << a << '\n' << "b is " << b << endl;

b = 1;
cout << (a = --b ? b : (b = -99)) << '\n' << "a is " << a << '\n' << "b is " << b << endl;


}

The output of the program is:

-99

a is 0

b is -99

-99

a is -99

b is -99

On the first segment of code what I understand is that a is given the value --b, 0, so it becomes false, so b=-99 is executed. I can't understand the second segment of code, where a=--b has no parentheses, why a is given the value -99.


Solution

  • (a = --b ? b : (b = -99))
    

    here, because = and ? have the same priority (15 according to the link provided) and are evaluated from right to left, it is executed as follows:

    a = --b ? b : (b = -99)
    1. --b ( =0)
    2. 0?
    3. 0 so not what is immediately after ? but what is after :
    4. b=-99 (evaluate second expression)
    5. a = -99 (assign the result of expression)