为什么当我调用 factorial
函数时它什么也没做?
这是实现阶乘函数的正确方法吗?
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n-1);
}
}
int main()
{
int x = 3;
cout << x << endl;
factorial(x);
cout << x;
return 0;
}
最佳答案
factorial
的结果被丢弃,即未绑定(bind)到要进一步处理的变量。修复很简单:
const int result = factorial(x);
cout << "The result is " << result << "\n";
这是一个很好的演示,当 C++17 nodiscard属性可能会有所帮助。如果函数签名显示为
[[nodiscard]] int factorial(int n)
编译器会在返回值未绑定(bind)到变量时报错,例如
factorial(42); // warning: ignoring return value of 'int factorial(int)', declared with attribute nodiscard [-Wunused-result]
关于c++ - 在 C++ 中不执行任何操作的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52606219/