What is the output of the following program? #include <stdio.h> int funcf (int…
2004
What is the output of the following program?
#include <stdio.h>
int funcf (int x);
int funcg (int y);
main()
{
int x = 5, y = 10, count;
for (count = 1; count <= 2; ++count)
{
y += funcf(x) + funcg(x);
printf ("%d ", y);
}
}
funcf(int x)
{
int y;
y = funcg(x);
return (y);
}
funcg(int x)
{
static int y = 10;
y += 1;
return (y+x);
}
- A.
43 80
- B.
42 74
- C.
33 37
- D.
32 32
Attempted by 21 students.
Show answer & explanation
Correct answer: A
Key idea: funcg has a static variable that persists across calls and is incremented each time funcg runs. funcf simply calls funcg and returns its result, so each loop iteration calls funcg twice.
Initial values: main's x = 5, main's y = 10. static y inside funcg is initialized to 10.
First loop iteration:
funcf(x) calls funcg: static y increments 10 -> 11, funcg returns 11 + 5 = 16.
The direct call funcg(x): static y increments 11 -> 12, funcg returns 12 + 5 = 17.
Sum added to main's y = 16 + 17 = 33, so main's y becomes 10 + 33 = 43. Program prints 43.
Second loop iteration:
funcf(x) calls funcg: static y increments 12 -> 13, funcg returns 13 + 5 = 18.
The direct call funcg(x): static y increments 13 -> 14, funcg returns 14 + 5 = 19.
Sum added to main's y = 18 + 19 = 37, so main's y becomes 43 + 37 = 80. Program prints 80.
Final output: 43 80
Note: The result depends on the order in which the two function calls are executed because funcg modifies a static variable. The trace above shows the sequence where funcf (which calls funcg) runs before the separate funcg call, producing the shown output.