Code:
int alg(int n, int counter) {
using namespace std;
if (n == 1)
return counter;
else {
if (n % 2 == 1)
alg(3*n+1, ++counter);
else
alg(n/2, ++counter);
}
}
The bold part is the only part of the function that returns something meaningful. If you don't return anything from other parts of the function, whatever happens to be at a particular spot on the stack gets used as the "result".
And it should be pretty easy for the compiler to see, that the if branch returns something whereas the else part doesn't. Turn on warning diagnostics (e.g -Wall for GCC)
What it should be:
Code:
int alg(int n, int counter) {
using namespace std;
if (n == 1)
return counter;
else {
if (n % 2 == 1)
return alg(3*n+1, ++counter);
else
return alg(n/2, ++counter);
}
}
Now you can easily see that each execution path through the function ends with a return statement.