Pregunta

#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.

¿Fue útil?

Solución

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.

Otros consejos

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

The order of evaluation is unsequenced and hence it is unspecified behavior either a(x) or x could be evaluated first. With respect to the C++ draft standard section 1.9 Program execution paragraph 15 says(emphasis mine):

[...]Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] [...]

and it may even differ between different evaluations and furthmore if we go back to paragraph 13 it says:

[...]If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced. [ Note: The execution of unsequenced evaluations can overlap. —end note ] Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which.[...]

which explains that this is unspecified behavior.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top