Question

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.

Was it helpful?

Solution 2

(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)

OTHER TIPS

This is because = has the same priority as ?: (C++ operator priorities). In such case, and because they have right-to-left associativity, they are evaluated from right to left. So at first the expression --b ? b : (b = -99) is evaluated into -99 and then it is being assigned to a.

The ternary operator has right-to-left associativity, and the same precedence as assignment which means that the condition term the the second segment is interpreted to be a = ( --b ? b : (b = -99))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top