I made a mistake when I made a recursion function whose purpose is get a largest fibonacci value in Integer32 in c++.
The mistake I made was
int get_largest_in_fibonacci(int before, int current){
if(current < 0){
return before;
}else{
get_largest_in_fibonacci(current, before + current);
// should have been
// return get_largest_in_fibonacci(current, before + current);
}
}
I didn't return in the else statement.
But In this question that's not I want to know.
int main(){
cout << "result : " << get_largest_in_fibonacci(1,1) << '\n';
return 0;
}
In this main(), The result was result : 2
. But I can't understand where does 2 come from.
Because, That badly behaving function can't return a value.
At first, I thought the argument (1,1)
would have been able to 2 in somewhere.
So I changed their value like (3,5) but the result was same.
And then I thought maybe that could be a garbage value.
But I think garbage value almost always keep giving me random "big" number, but that was not the case in here.
And after I changed the main()
little bit like this.
int main(){
int result = get_largest_in_fibonacci(1,1);
cout << "result : " << result << '\n';
return 0;
}
Just assigned the function result to int result
.
But In this time, the result was result : 0
.
So I wonder how did the get_largest_in_fibonacci
returned in the first place, and how does return value changed by just assigning it to int variable?