Adnan Selimovic
Adnan Selimovic

Reputation: 55

cout variable and function that change variable by reference

Suppose we have next code:

#include<iostream>

using namespace std;

int change(int &temp){
    temp += 2;
    return 10;
}

int main(){
    int nmb = 2;

    cout << change(nmb) << " " << nmb << endl;
}

I thought it should work like cout would print out new value of nmb but it prints the old version of nmb.

Instead of wanted result 10 4, I get the result 10 2. Why does cout prints out old value of nmb, as cout first print out change then it prints nmb?

I have compiled it under g++, using standard c++11.

Upvotes: 2

Views: 214

Answers (2)

Del
Del

Reputation: 1309

No, the order of evaluation is implementation defined.

The order of evaluation is unspecified until C++17. (Please see the comments and M.M's answer.)

http://en.cppreference.com/w/cpp/language/eval_order

Upvotes: 5

M.M
M.M

Reputation: 141554

Since C++17, the operator<< has left-right sequencing (i.e. the left operand is sequenced before the right operand). So if you use a compiler that conforms to the latest standard you should see 10 4. (Ref: N4659 [over.match.oper]/2, [expr.shift]/4)

Prior to C++17 it was unspecified.

Upvotes: 4

Related Questions