Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong output while running C code [duplicate]

Tags:

c

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;
    }
like image 350
user1543957 Avatar asked Oct 25 '12 07:10

user1543957


3 Answers

you are expecting func(4) to be called before func(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.

like image 120
P.P Avatar answered Oct 01 '22 03:10

P.P


The order of evaluation of func(4) and func(5) isn't defined by the C standard(s).

like image 34
Andreas Brinck Avatar answered Oct 01 '22 03:10

Andreas Brinck


The order of evaluation of expression is unspecified behaviour hence func(4) and func(5) may be called in different order as you supposed to

You might like to visit it for more

Compilers and argument order of evaluation in C++

Parameter evaluation order before a function calling in C

like image 42
Omkant Avatar answered Oct 01 '22 02:10

Omkant