I am trying to grok the comma operator. The reference says:
In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (...), and its side effects are completed before evaluation of the expression E2 begins (...).
I am unable to grok the clause - "... the expression E1 is evaluated, its result is discarded (...), and its side effects are completed before...". Specifically, what is retained and what is discarded?
For e.g., in the example from this SO answer:
int x = 0;
int y = some_number;
for(; x < y; ++x, --y)
{
// Do something which uses a converging x and y
}
When we do a ++x
, what is the 'result' (that is discarded) and what is the 'side-effect' (that is 'completed' and perhaps 'retained')? Shouldn't the result of ++x
be discarded and the value of x
remain unchanged? Working example showing incrementation of x
is here.
In other words, given a certain expression, how do I deduce if it will be evaluated and its results would be discarded, or if it is a side-effect and its results would perhaps be computed and retained?
In C++ an expression can result in a value and can cause side effects. In the expression ++x, --y
you have two sub expressions forming the whole expression. The left, ++x
returns x
after increment, and the right returns y
after decrement. The expression will return the right side of the comma (y
) rather than the left side x
.
The side effects of the left hand side are preserved, so x
is still incremented.
This might make more sense if you were looking to perform assignment.
int x = 1;
int y = 1;
int& z = (++x, --y);
std::cout << z << std::endl;
z
becomes a reference to y
and thus we will print 0