其他分享
首页 > 其他分享> > C通过参考和通过值函数的副作用?

C通过参考和通过值函数的副作用?

作者:互联网

我理解为什么这样可行

#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

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

#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

解决方法:

您遇到了未定义的行为.第二个版本修改你在第二个cout中读取的a的值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

标签:c,pass-by-reference,pass-by-value
来源: https://codeday.me/bug/20190901/1783412.html