3

我明白为什么会这样

#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
4

2 回答 2

5

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

第一个版本:

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
于 2012-12-13T19:46:52.053 回答
0

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

于 2012-12-13T20:01:10.267 回答