Comma operator

closed account (EwCjE3v7)
I do not get how the value of y is not 16, could someone explain why?

1
2
3
4
5
    bool someValue = true;
    int x = 5, y = 15;

    someValue ? ++x, ++y : --x, --y;
    cout << x << " " << y << endl;
The comma operator has the lowest precedence, so this is actually

( someValue ? ++x, ++y : --x ) , --y;
closed account (EwCjE3v7)
Try the program and make sure someValue is true, it'll only increment I not j :/ so



You think it's going to be 16 because your brain is assuming this:

 
someValue ? (++x, ++y) : (--x, --y);

But it's actually as Cubbi describes.
Last edited on
Exactly.
1
2
3
4
5
if (someValue)
    ++x, ++y;
else
    --x;
--y;
btw:
someValue ? ++x, ++y : --x, --y;
is a horrible line of code :)
closed account (EwCjE3v7)
No I meant this, see the picture.
http://postimg.org/image/4xvq0h72l/

Only x is incremented, why is y not incremented?
Both x and y are incremented. Only y is decremented.
http://www.cplusplus.com/forum/beginner/127163/#msg688141
closed account (EwCjE3v7)
OH lol, just relised but what I dont get is would the ?: not need a Semi colon to end it?
Last edited on
A semicolon only ends statements. With the comma operator, you can have infinitely many expressions in a statement.
Topic archived. No new replies allowed.