in Programming edited by
9,218 views
36 votes
36 votes

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 ______.

in Programming edited by
9.2k views

2 Answers

57 votes
57 votes
Best answer
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$
edited by

4 Comments

@Pranavpurkar These were my thoughts exactly. 

@MohanK 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.

@Arjun Sir, please clarify. 

 

0
0

@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.

0
0

@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
1
7 votes
7 votes
1+26+51+100+52

=230

2 Comments

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

Related questions