GATE / CS ARCHIVE

GATE CSE 2019 / QUESTION 27

Static state and for-loop evaluation order

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

GATE 2019, Q27 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 27, GATE 2019: r() contains static int num=7 and returns num--. main executes for(r(); r(); r()) printf("%d",r()); then returns. Which displayed output is correct: A 41, B 52, C 63, D 630?
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (29 steps)

1. A static local variable is initialized once and keeps its value between calls. Post-decrement returns the old num and then reduces the stored value by one.
2. A for loop evaluates its initializer once, then repeatedly evaluates condition, body, and increment in that order. Calls in the initializer and increment still change num even though their returned values are discarded.
3. The initializer returns 7 and leaves num=6. The first condition returns 6, which is true, and leaves num=5. The body returns and prints 5, leaving num=4. The increment returns 4 and leaves num=3.
4. The second condition returns 3, so the body prints 2 and leaves num=1. The increment returns 1 and leaves num=0. The next condition returns 0, which is false, so there is no third body execution.
5. Only body calls print. No space or newline separates the two digits, so the displayed output is 52, option B. In particular, the zero used to stop the loop is never printed.

Original paper, page 9 · Answer key