Consider the following C program. #include<stdio.h> int f1(void); int…
2015
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 ________.
Attempted by 107 students.
Show answer & explanation
Correct answer: 230
Answer: 230
Explanation:
Call to f1: it declares a local x = 25, then increments and returns 26.
First call to f2: static x starts at 50, is incremented to 51 and returns 51.
Call to f3: it multiplies the global x (initially 10) by 10, changing the global x to 100 and returning 100.
Second call to f2: the static x is incremented again from 51 to 52 and returns 52.
Compute the sum returned by the functions: 26 + 51 + 100 + 52 = 229.
Add this to the local x in main (initially 1): 1 + 229 = 230.
Therefore, the program prints 230.
Note: The C standard does not guarantee the order of evaluation of the operands of +, but in this program the final result is the same regardless of evaluation order because the functions' side effects do not interfere in a way that changes the computed sum.
A video solution is available for this question — log in and enroll to watch it.