简体   繁体   中英

C++ Pass by Reference and Pass by Value Functions side effect?

I understand why this works as it does

#include <iostream>
using namespace std;

int additionFive (int a)
{
    a = a - 5;
    return a;
}

int subtractFive (int &a)
{
    a = a -5;
    return a;
}

int main()
{
    int local_A = 10;

    cout << "Answer: " << additionFive(local_A) << endl;
    cout << "local_A Value "<< local_A << endl;

    cout << "Answer: " << subtractFive(local_A) << endl;
    cout << "local_A = Value "<< local_A << endl;

    return 0;
}

OUTPUT:

Answer: 5
local_A Value 10
Answer: 5
local_A = Value 5

But I dont understand why this change of syntax changes the answer (simply putting the arithmetic and print out on the same line)

#include <iostream>
using namespace std;

int additionFive (int a)
{
    a = a - 5;
    return a;
}

int subtractFive (int &a)
{
    a = a -5;
    return a;
}

int main()
{
    int local_A = 10;

    cout << "Answer: " << additionFive(local_A) << " local_A Value: "<< local_A << endl;
    cout << "Answer: " << subtractFive(local_A) << " local_A = Value: "<< local_A << endl;

    return 0;
}

OUTPUT:

Answer: 5 local_A Value: 10
Answer: 5 local_A = Value: 10

You're running into undefined behavior . The second version modifies the value of a which you're reading in the second cout 2 times, with no sequence points in between the reads.

First version:

cout << "Answer: " << subtractFive(local_A) << endl;
//                              |                  |
//                  reads and modifies local_A     |
//                                           sequence point
cout << "local_A Value ="<< local_A << endl;
//                             |
//                       reads local_A

Second version:

cout << "Answer: " << subtractFive(local_A) << " local_A Value: "<< local_A << endl;
//                             |                                       |
//                  reads and modifies local_A                   reads local_A

Well the behavior of the second code is completely system/compiler depended. On Dev C++ the second code is giving the same output as first one. It depends on how the compiler builds the cout statement in program assembly...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM