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?

Choose one option
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:

  1. Initialization: r() is called. Returns 77, num becomes 66.
  2. Condition check: r() is called. Returns 66 (non-zero / true), num becomes 55.
  3. Loop body: printf("%d", r()) calls r(). Returns 55, num becomes 44. Output: 5.
  4. Step / Increment: r() is called. Returns 44, num becomes 33.

Iteration 2:
5. Condition check: r() is called. Returns 33 (non-zero / true), num becomes 22.
6. Loop body: printf("%d", r()) calls r(). Returns 22, num becomes 11. Output: 2.
7. Step / Increment: r() is called. Returns 11, num becomes 00.

Termination:
8. Condition check: r() is called. Returns 00 (zero / false). The loop terminates!
(num becomes −1-1).

The values printed by the program are 52.

Final answer

B

Common trap

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.