My concern is about what will use stack memory in an instruction involving arithmetics and a recursive function call such as:
return 5 + f(a-1); //f is recursive
I'd like to understand what is put on the stack, and when, so that I know what could or couldn't cause memory issues in case of a deep recursion. Here is a more complete example:
int f(int a) {
if (a > 0) {
return 5 + f(a-1);
}
else {
return 0;
}
}
Let's focus on the line return 5 + f(a-1);
What will we have to store in memory around that point?
- We do have a place in the stack for the integer a since the variable is local to f
- will the values 5 and 1 be stored?
- what about the result of the operation a-1, will it be put on the stack?
- what about the return value of f?
The "worst case" scenario regarding the amount of memory used would be that at some point all of these will be on the stack at the same time. A better case would be that there will be allocations and deallocations in sequence such that not everything is kept in memory.
How will it happen? Is it up to the compiler?
Many thanks,