In C++
, it is possible to do the following:
int f(int& a, int& b, int& c, int& d) {
return (a, b, c, d); // here
}
First, what is the name in the language (and link on cppreference) to this "parenthesis" expression where only the last term is returned;
Second, let's say the code becomes:
int f(int& a, int& b, int& c, int& d) {
return (a += 2, d += 5, b -= 3, c = a + b + d, d); // here
}
Is the order of evaluation of theses "parenthesis" expressions fixed? If so do I have the guarantee that f
will change the values of a
, b
, c
and d
from the left to the right, and return the correct updated value of d
as if it was:
int f(int& a, int& b, int& c, int& d) {
a += 2;
d += 5;
b -= 3;
c = a + b + d;
return d;
}
Finally, purely in C++11
(since the problem don't exist in C++14
anymore because constexpr
don't have such strong requirements), can this parentheses expressions be used to write several computation in a single constexpr
function?
First, what is the name in the language (and link on cppreference) to this "parenthesis" expression where only the last term is returned;
I mean: the comma operator evaluate but discard the element on the left and return the element on the right (if the element on the left isn't an object with comma operator redefined).
And there is no need of parenthesis; you can also write.
return a, b, c, d;
Second, let's say the code becomes [...] Is the order of evaluation of theses "parenthesis" expressions fixed?
Yes; from left to right.
Look for "sequence point" for more info.
And from
return a += 2, d += 5, b -= 3, c = a + b + d, d;
you get exactly the same result that you get from
a += 2; d += 5; b -= 3; c = a + b + d; return d;
taking also in count that a
, d
, b
and c
are int
s and that int
isn't a class that redefine the comma operator.
But do not confuse the comma in "comma operator" with the comma that separate the arguments in a function calling. The first one is a "sequence point", the second one isn't.
I mean: with
int i = 0;
return i++, i++, i++;
the returned value is defined (2); if foo()
is a function that receive three integers, with
int i = 0;
foo(i++, i++, i++);
you know that foo()
receive a zero, a one and a two but the order is unspecified (can be 0
for the first parameter and 2
for the third or the contrary).
Finally, purely in C++11 [...] can this parentheses expressions be used to write several computation in a single constexpr function?
Yes.
And (IMHO) it's a very useful feature.