c++ - 在 C++ 中不执行任何操作的函数调用

标签 c++ return-value

为什么当我调用 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/

相关文章:

c++ - 为什么 std::basic_string::substr 不遵循 [begin, end) 约定?

c++ - AnsiString 作为 Embarcadero C++ Builder 中类型字符串的默认值?

assembly - 返回值是如何在汇编级实现的?

php - 返回空字符串或空值是否有更多优势?

javascript - DotNetBrowser 调用 JS 函数并从 C# 返回值

c# - 未分配的变量和 "Not all code paths return a value"解决方法?

c++ - 是否可以通过在 matlab 中调用 c/c++ 代码来加速 matlab 绘图?

c++ - 在 boost::spirit mini_c 中实现 "NOT"

c++ - Linux 下的 C C++ 图形程序

ruby - Ruby 中的隐式返回值是怎么回事?