GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 89

Local shadowing and pointer update of a global

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2003 paper

GATE 2003, Q89 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 89, GATE 2003: Consider this C-style program (print emits its integer argument followed by a space):
int x;
void Q(int z) { z+=x; print(z); }
void P(int *y) {
  int x=*y+2;
  Q(x);
  *y=x-1;
  print(x);
}
main(void) { x=5; P(&x); print(x); }
What output is produced?
A. 12 7 6  B. 22 12 11  C. 14 6 6  D. 7 6 6
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. main sets the global x to 5 and passes its address, so y inside P points to that global object.
2. P declares a different, local x and initializes it to *y+2=5+2=7. Calling Q(x) copies 7 into Q's parameter z.
3. Q has no local x, so its x denotes the global, still 5. z becomes 7+5=12 and Q prints 12; this does not alter either x.
4. Back in P, *y=x−1 uses local x=7 on the right and writes 6 to the global through y. P prints its unchanged local 7.
5. main finally prints global x=6, producing 12 7 6, A. Passing the pointer allows the global update despite P's name shadowing.

Solution: main sets global x=5 and passes its address to P. P's local x becomes *y+2=7 and shadows the global only inside P. Q receives z=7; its unqualified x is the global 5, so z becomes 12 and Q prints 12. Returning to P, *y=x−1 writes 6 to the global, but P's local remains 7 and is printed. Finally main prints the global 6. The output is 12 7 6, A.

Original paper, page 13