Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 204
Sukhanov Niсkolay Avatar asked Dec 01 '22 20:12

Sukhanov Niсkolay


2 Answers

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.

like image 60
Daniel Frey Avatar answered Dec 05 '22 13:12

Daniel Frey


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

like image 23
LihO Avatar answered Dec 05 '22 13:12

LihO