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;
}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With