我正在尝试理解以下代码。当我逐行调试时,当我第二次调用“ addOne”时,变量“ a”变为12。 “ myInt”也更改为12,但是一旦转到“ cout”语句,“ myInt”将再次变为11,并且将输出11。 我想知道为什么将12分配回'myInt'首先将其更改为12,但是一旦我将其打印出来,它将再次变为11?
感谢所有帮助!
为使其打印输出12,我将'a ++'更改为'++ a'起作用。一旦它是'a ++',如果我更改语句我的'myInt = addOne(myInt);'到“ addOne(myInt);”它仍然打印出12。
#include <iostream>
using namespace std;
int addOne(int& a);
int main() {
int myInt = 10;
cout << "Before calling addOne myInt = " << myInt << endl;
addOne(myInt); //Notice not storing result
cout << "After calling addOne myInt = " << myInt << endl;
myInt = addOne(myInt); //Notice storing result as myInt
cout << "After returning results of function call as myInt = " << myInt << endl;
return 0;
}
int addOne(int& a) {
cout << "During addOne call myInt = " << a << endl;
return (a++); //What happens if we use a++ instead of ++a?
}