C ++ Pass by Reference和Pass by Value Functions的副作用?

时间:2012-12-13 19:45:22

标签: c++ pass-by-reference pass-by-value

我明白为什么会这样做

#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;
}

输出:

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

但我不明白为什么这种语法变化会改变答案(简单地将算术和打印输出在同一行上)

#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;
}

输出:

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

2 个答案:

答案 0 :(得分:5)

您正在遇到未定义的行为。第二个版本修改了您在第二个a中读取的cout的值2次,读取之间没有序列点。

第一版:

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

第二版:

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

答案 1 :(得分:0)

第二个代码的行为完全取决于系统/编译器。在Dev C ++上,第二个代码提供与第一个相同的输出。这取决于编译器如何在程序集中构建cout语句......