Question
Consider the following C program:
#include <stdio.h>
int r(){
static int num = 7;
return num--;
}
int main(){
for (r(); r(); r())
printf("%d", r());
return 0;
}
Which one of the following values will be displayed on execution of the programs?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2019 answer key
Solution
Trace the execution order of the for loop components and track the static variable.
The function r() defines a static variable num initialized to 7:
int r(){
static int num = 7;
return num--;
}
Because num is static, its value persists across calls. The post-decrement num-- returns the current value and then decrements num by 1.
The loop structure is:
for (r(); r(); r())
printf("%d", r());
Let us trace each call to r() in exact execution order:
Iteration 1:
- Initialization:
r()is called. Returns ,numbecomes . - Condition check:
r()is called. Returns (non-zero / true),numbecomes . - Loop body:
printf("%d", r())callsr(). Returns ,numbecomes . Output:5. - Step / Increment:
r()is called. Returns ,numbecomes .
Iteration 2:
5. Condition check: r() is called. Returns (non-zero / true), num becomes .
6. Loop body: printf("%d", r()) calls r(). Returns , num becomes . Output: 2.
7. Step / Increment: r() is called. Returns , num becomes .
Termination:
8. Condition check: r() is called. Returns (zero / false). The loop terminates!
(num becomes ).
The values printed by the program are 52.
B
Missing one of the calls to r() in the for loop header (initialization, condition, and increment each call r()).
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2019 Computer Science and Information Technology (CS)
- Question
- 37 of 65, printed as CS Q.27
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.