Possible Duplicate:
Parameter evaluation order before a function calling in C
For the below code I expected the output to be 20 and 76 but instead 75 and 21 is comming as output .Please explain why is so.
#include<stdio.h>
unsigned func(unsigned n)
{
unsigned int a =1 ;
static unsigned int b=2;
a+=b; b+=a;
{
unsigned int a=3;
a+=b; b+=a;
}
//printf("%d %d ",a,b);
return (n+a+b);
}
int main()
{
printf("%d %d\n",func(4),func(5));
return 0;
}
There is a well known term for this called "function side effects". You change a variable inside a function, call the function and rely upon a statement using the variable expecting it to have already changed. Generally this should be avoided and is not a good approach.
A better alternate in such a scenario is either call function and store the return values and then use them in printf or make two different printf calls.
side effects
The order of evaluation of func(4) and func(5) isn't defined by the C standard(s).
Order of evaluation could be the reason. Because,
prints
The arguments are pushed onto stack in reverse order. It seems in your compiler implementation,
func(5)
is called beforefunc(4)
.The code is simple, and remember
static
variables will preserve their values between function calls.In your program, due to your compiler(thus compiler specific, not defined by standards):
func(5)
is executed first, : which returns 21.. explanation:func(4) is executed next,
explanation:
Hence the output.
you are expecting
func(4)
to be called beforefunc(5)
but the opposite happens with your compiler. The order of evaluation of function parameters is unspecified by C standard. So, compiler is free choose which function to call first. So across different runs you may observe different order of function calls, though it's very unlikely to happen that way with the same compiler.