Strange behavior of std :: cout in C ++

#include <iostream>

int a(int &x) {
    x = -1;
    return x;
}

int main () {
    int x = 5;
    std::cout << a(x) << " " << x << std::endl;
}

Why is the output "-1 5"?

PS: compiler:

i686-apple-darwin11-llvm-g ++ - 4.2 (GCC) 4.2.1 (based on the assembly of Apple Inc. 5658) (LLVM build 2336.11.00)

PS: compiled without any optimization.

+4
source share
3 answers

In this line:

std::cout << a(x) << " " << x << std::endl;

assessment procedure a(x)and xnot specified. This behavior is unspecified what happens in your case, the compiler has decided to first assess x, a(x).

+14
source

, a(x) x, [1]. , x ( , ), :

int x = 5;
int y = a(x);
std::cout << y << " " << x << std::endl;

[1] " , , , , ". 5 , § 4

+3

, , a(x) x.

[...] , , . [. , , . -end note] [...]

, 13, :

[...] If A is not sequenced before B and B are not sequenced to A, then A and B are not sequenced . [Note. Unexplored assessments may overlap. -end note] Scores A and B are indefinitely sequenced when either A is sequenced before B or B is sequenced to A, but it is not specified which . [...]

which explains that this is vague behavior.

+1
source

All Articles