#include <iostream>
int a(int &x) {
x = -1;
return x;
}
int main () {
int x = 5;
std::cout << a(x) << " " << x << std::endl;
}
Why output is "-1 5"?
PS: compiler is:
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
PS: compiled without any optimization.
In this line:
std::cout << a(x) << " " << x << std::endl;
the order of evaluation of a(x)
and x
is not specified. It's unspecified behaviour what happens, in your case the compiler decided to evaluate x
first, a(x)
afterwards.
The order, in which a(x)
and x
are being evaluated is unspecified [1]. To make sure that x
will not be modified within the same expression (and avoiding unspecified behavior by doing so), you could do:
int x = 5;
int y = a(x);
std::cout << y << " " << x << std::endl;
[1] "Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. " 5 Expressions, §4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With