This code gives output as 125
#include<stdio.h>
int func(int a)
{
static int num = 2;
if(a==0) return 1;
num ;
return num*func(--a);
}
int main()
{
printf("%d", func(3));
}
While this code gives output as 60
#include<stdio.h>
int func(int a)
{
static int num = 2;
if(a==0) return 1;
return ( num)*func(--a);
}
int main()
{
printf("%d", func(3));
}
In the first code I incremented num
before return statement, in second code I pre-incremented num
in the return statement.
The first code seems to be evaluating to 5*5*5, while the second evaluates to 3*4*5. Why is it so?
CodePudding user response:
On this line in the second program:
return ( num)*func(--a);
The value of num
is incremented as a side effect, and the function call to func
also modifies num
.
The evaluation of the individual operands of this expression are unsequenced, which means that either num
may be evaluated first or that func
may be called first.
The call to func
does introduce a sequence point. So if num
is evaluated first, the side effect of incrementing num
is applied before func
is actually called. On the other hand, if the call to func
is evaluated first, num
will be modified inside of the function call and then the read and update of num
will see the updated value. However, there's no guarantee that one or the other will happen first.
So there's no undefined behavior here, however the result is unspecified due to the unsequenced evaluation of the subexpressions.
The first program has a similar issue, even though num
isn't incremented in the same statement:
return num*func(--a);
Just as before, if num
is evaluated first then the current value is seen. If the function call is evaluated first, then the updated value of num
will be read.
To get deterministic behavior from your program, you'll need to copy the current value of the static variable to a non-static variable and use that value to multiply by the function result.
int func(int a)
{
static int num = 2;
if(a==0) return 1;
int num_tmp = num;
return num_tmp*func(--a);
}