In C, predict the output and trace scope and parameter shadowing carefully. #include<stdio.h> int i; int fun1(int); int fun2(int); int main() { extern int j; int i=3; fun1(i); printf("%d,", i); fun2(i); printf("%d", i); return 0; } int fun1(int j) { printf("%d,", ++j); return 0; } int fun2(int i) { printf("%d,", ++i); return 0; } int j=1;

Difficulty: Medium

Correct Answer: 4, 3, 4, 3

Explanation:


Introduction / Context:
This question checks understanding of variable scope, shadowing, parameter passing by value, and the order of prints. Local variables can shadow globals, and function parameters are copies, so increments inside functions do not modify the caller’s variable.


Given Data / Assumptions:

  • Global i (unused effectively) and global j = 1.
  • Main declares local i = 3, shadowing global i.
  • fun1 takes parameter j (by value) and pre-increments it.
  • fun2 takes parameter i (by value) and pre-increments it.


Concept / Approach:
Each function prints its own incremented parameter. The main’s local i remains unchanged because C passes arguments by value. The sequence of prints is crucial: fun1 → main print → fun2 → main print.


Step-by-Step Solution:
Call fun1(i) with i = 3 → parameter j = 3 → ++j = 4, prints "4,".Back in main, print i (still 3) → prints "3,".Call fun2(i) with i = 3 → parameter i = 3 → ++i = 4, prints "4,".Back in main, print i (still 3) → prints "3".


Verification / Alternative check:
Add explicit addresses or change parameter names; you will still observe call-by-value behavior and the same print order.


Why Other Options Are Wrong:
Any option that changes the second or fourth value misunderstands that main’s i remains 3. Options with leading 3 ignore the pre-increment inside fun1.


Common Pitfalls:
Confusing extern j with parameter j; the parameter hides the global name within fun1’s scope. Also, assuming pass-by-reference when C uses pass-by-value.


Final Answer:
4, 3, 4, 3

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion