What does this mean? A exercise from C++ Primer. (someValue ? ++x, ++y : --x, --y)

due to the precedence and associativity, the ?: operator is higher precedence than the comma operator. comma is left associativity while ?: is right.

The exercise ask me to figure out what does the following code mean?

 
  someValue ? ++x, ++y : --x, --y
If you want to figure out what code does, run it. Then read on operators and try to figure out how that happened.

If you read on ternary operator, you will know that part between ? and : behaves as if it was inside brackets (precedence of inner operators has no relation on behavior outside this part): someValue ? (++x, ++y) : --x, --y Then, because comma has lower precedence rest of code parsed as: (someValue ? ++x, ++y : --x), --y

So, depending on value of somevalue it either increments both x and y or decrements x. Then it unconditionlly decrements y.
I hate cruft like that. Why not just write:

1
2
if (somevalue) { ++x; ++y; }
else           { --x; --y; }

So much easier to read, and you don't have to scratch the back of your brain to remember whether or not : is a sequence point. (It is.)
Duoas wrote:
I hate cruft like that. Why not just write:
Another example why ternary operator should not be abused like that: it is easy to misread it — your code does not do what original does.
It is actually:
1
2
3
4
//direct transition
if (somevalue) { ++x; ++y; }
else           { --x; }
 --y;
//Assuming no side effects of increment/decrement
if (somevalue) { ++x;}
else           { --x; --y; }
Yup. Nice catch!
Topic archived. No new replies allowed.