9,218 views

Consider the following C program:

#include<stdio.h>
int f1(void);
int f2(void);
int f3(void);
int x=10;
int main()
{
int x=1;
x += f1() + f2 () + f3() + f2();
printf("%d", x);
return 0;
}
int f1() { int x = 25; x++; return x;}
int f2() { static int x = 50; x++; return x;}
int f3() { x *= 10; return x;}

The output of the program is ______.

The variable $x$ is initialized to $1$. First and only call to $f1()$ returns $26$. First call to $f2()$ returns $51$. First and only call to $f3()$ returns $100$. Second call to $f2()$ returns $52$ (The value of local static variable $x$ in $f2()$ retains its previous value $51$ and is incremented by $1$).

$$x=1+26+51+100+52 = 230$$

Answer: $230$

@Pranavpurkar These were my thoughts exactly.

I too have the same doubt. What I learned is that the order of function calls is unpredictable.

If the above thoughts turn out to be true then, my answer would vary from  compiler to compiler.

@Pranavpurkar first return value copied to parent, after that function will be removed from stack.

@MohanK There's no hard to evaluate first f1() then f2()... You can do by your choice of order. However output will be same.

@Pranavpurkar The value of $x$ computed in $f1()$ will first be given to parent before the function call is popped out from the stack . Hence we will get a return value of $26$.

1+26+51+100+52

=230

In main, x is declared and initialized and x is declared globally in the program, that means global variable will get priority during execution ?
Global has Least Priority.