I've been exploring the behaviour of static variables in C, using the following piece of code:
#include <stdio.h>
int f(int n)
{
static int r = 10;
if (n <= 0)
return 7;
if (n > 2)
return f(n-1) + r; // Important line
else{
r = 17;
return f(n-1) + n;
}
}
int main(void)
{
int n = 4;
printf("%d\n", f(n));
return 0;
}
Now if you note the "Important line" in the code (return f(n-1) + r), it calls the function f first, which changes the static variable, r.
However, if I changed that line to return r + f(n-1), I expect that r will get stored in a temporary register, and only then will the function f be evaluated. However this does not seem to happen, as in both the cases, the function f is evaluated first. I've even checked the assembly code generated by the compiler and it calls the function first in both cases.
But, if I change the line to return (r+2) + f(n-1), then (r+2) is evaluated first and stored in a temporary register and only then is the function f evaluated.
And if I again change the line to return f(n-1) + (r+2) then it's the function f that gets evaluated first.
Thus, using return r + f(n-1) and return f(n-1) + r in the program give the exact same output.
However, using return (r+2) + f(n-1) and return f(n-1) + (r+2) gives different outputs.
I can't understand why this discrepancy in the behaviour of static variables. According to my understanding, in return r + f(n-1) clearly r should be evaluated first, but this is not happening. Can anyone please explain why ? And why is this behaviour not consistent ? Why does it change if I use (r+2) instead of r ?