Reputation: 85
#include <iostream>
using namespace std;
int main() {
int n,x;
int fact(int);
cin >> n;
x = fact(n);
cout << x;
return 0;
}
int fact(int n) {
if(n!=1)
return n*fact(n-1);
}
In the last case, when the argument passed to the function fact is 1, how is it able to calculate that fact(1)
is equal to 1, without me specifying it in my code?
Upvotes: 1
Views: 119
Reputation: 21
int fact(int n);
This function signature returns an integer, but when n=1 is given there is no corresponding return statement in your implementation. In that case, the function may return any int
value (i.e. garbage in memory) and the behaviour is undefined. You should not depend on this, even though your compiler allows it to run.
I'm quite certain you saw a warning when compiling your program. In my environment (g++ on Mac OSX), the compiler issued the following warning:
warning: control may reach end of non-void function [-Wreturn-type]
Personally, I don't think there is any good reason for a compiler to allow this kind of bug (i.e. it should fail to compile).
Reference: A similar question is found below:
C++ return value without return statement
Upvotes: 2
Reputation: 4468
This program relies on undefined behavior. It is certainly not guaranteed to work, but you may have found a situation in which the parameter you send (1) is in a place where the calling code perceives it as the return value. Do not depend on this behavior.
Many C++ compilers would reject this code as having a semantic issue: Not all control paths return a value from fact()
Upvotes: 10