Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function calls that don't do anything in C++

Why when I call the factorial function it doesn't do anything?

Is this the right way to implement a factorial function?

#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;
 }

1 Answers

The result of factorial is discarded, i.e., not bound to a variable to be processed further. The fix is simple:

const int result = factorial(x);

cout << "The result is " << result << "\n";

This is a nice demonstration when the C++17 nodiscard attribute can be helpful. If the function signature reads

[[nodiscard]] int factorial(int n)

compilers will complain when the return value is not bound to a variable, e.g.

factorial(42); // warning: ignoring return value of 'int factorial(int)', declared with attribute nodiscard [-Wunused-result]
like image 138
lubgr Avatar answered Jan 01 '26 17:01

lubgr