Function parameters evaluation order: is undefined behaviour if we pass reference?
Posted
by
bolov
on Stack Overflow
See other posts from Stack Overflow
or by bolov
Published on 2014-06-12T08:42:38Z
Indexed on
2014/06/12
9:24 UTC
Read the original article
Hit count: 274
This is undefined behaviour:
void feedMeValue(int x, int a) {
cout << x << " " << a << endl;
}
int main() {
int a = 2;
int &ra = a;
feedMeValue(ra = 3, a);
return 0;
}
because depending on what parameter gets evaluated first we could call (3, 2)
or (3, 3)
.
However this:
void feedMeReference(int x, int const &ref) {
cout << x << " " << ref << endl;
}
int main() {
int a = 2;
int &ra = a;
feedMeReference(ra = 3, a);
return 0;
}
will always output 3 3
since the second parameter is a reference and all parameters have been evaluated before the function call, so even if the second parameter is evaluated before of after ra = 3
, the function received a reference to a
wich will have a value of 2
or 3
at the time of the evaluation, but will always have the value 3
at the time of the function call.
Is the second example UB? It is important to know because the compiler is free to do anything if he detects undefined behaviour, even if I know it would always yield the same results.
*Note:
I think that feedMeReference(a = 3, a)
is the exact same situation as feedMeReference(ra = 3, a)
. However it seems not everybody agrees, in the addition to having 2 completely different answers.
© Stack Overflow or respective owner