用户定义的功能的意外返回值
Unexpected returned value of a user defined function
#include <iostream.h>
int someFunction(int &x, int c) {
c=c-1;
if(c==0) {
return 1;
}
x=x+1;
return someFunction(x,c) * x;
}
void main() {
int p = 5;
cout << someFunction(p,p);
}
此代码返回6561,但我不知道为什么。谁能帮助我?
您在这里有5个迭代:
1st iteration - C is 5 and reduced by 1 -> c=4 which is not 0 so we go on to "(++x) * someFunc".
2nd iteration - C is 4 and reduced by 1 -> c=3 which is not 0 so we go on to "(++x) * someFunc".
3rd iteration - C is 3 and reduced by 1 -> c=2 which is not 0 so we go on to "(++x) * someFunc".
4th iteration - C is 2 and reduced by 1 -> c=1 which is not 0 so we go on to "(++x) * someFunc".
5th iteration - C is 1 and reduced by 1 -> c=0 so we return 1.
在这一点上,我们有x * x * x * x * 1,在4个增量x = 9之后,因此值为9 * 9 * 9 * 9 * 9 * 1 = 6561
这是因为在发生实际乘法之前对函数进行评估,但是随着堆栈的放松,在每次乘法的时刻,通过参考传递的x
已经在其最后一个值中,即9。
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 程序不向函数返回值
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 用户定义的功能的意外返回值
- 打印函数会返回一个意外值,原因是什么
- GCC优化导致意外返回值