In C function-call nesting and assignment evaluation, what will this program print?
#include
int fun(int i)
{
i++;
return i;
}
int main()
{
int fun(int);
int i = 3;
fun(i = fun(fun(i)));
printf("%d
", i);
return 0;
}
-
A5
-
B4
-
CError
-
DGarbage value
-
EProgram-dependent
Answer
Correct Answer: 5
Explanation
Introduction / Context:This C question tests your understanding of expression evaluation with nested function calls, assignment as an expression, and pass-by-value semantics. Although the code looks compact, the exact order of operations determines the final value stored in the variable i.
Given Data / Assumptions:
- The helper function is int fun(int i) { i++; return i; }
- Initial value: i = 3
- Call sequence in main(): fun(i = fun(fun(i)));
- Platform-independent standard C behavior (no undefined behavior here).
Concept / Approach:The function fun returns its input plus one. Since arguments are passed by value, calls to fun never change the caller’s variable unless an assignment explicitly stores a return value. Also, assignment in C is an expression that yields the value assigned.
Step-by-Step Solution:Start with i = 3.Evaluate inner call: fun(i) → returns 4 (local increment), but i in main is still 3.Evaluate next call: fun(4) → returns 5.Perform assignment: i = 5 (assignment value is 5).Evaluate outer call: fun(5) → returns 6, result ignored.Print i which remains 5.
Verification / Alternative check:If you rewrote the line as i = fun(fun(fun(i))); then i would become 6. The difference is whether the final function call’s result is assigned back to i.
Why Other Options Are Wrong:“4” ignores the two nested increments. “Error” and “Garbage value” do not apply since the code compiles and runs definedly. “Program-dependent” is misleading; the behavior is well-defined in standard C.
Common Pitfalls:Mistaking pass-by-value for pass-by-reference; assuming all nested results are assigned; overlooking that the last fun call’s return is discarded.
Final Answer:5