Skip to main content

GATE CSE 2019Programming in C › General C Programming ConceptsVerified

GATE CSE 2019 PYQ: Consider the following C program: #include <stdio.h> int r () { static int num = 7 ; return num --; } int…

Consider the following C program:

  1. #include <stdio.h>
  2. int r() {
  3. static int num=7;
  4. return num--;
  5. }
  6. int main() {
  7. for (r();r();r())
  8. printf(“%d”,r());
  9. return 0;
  10. }

Which one of the following values will be displayed on execution of the programs?

  1. A
    41
  2. B
    52
    Correct answer
  3. C
    63
  4. D
    630

Answer

(B) 52 52 52

Approach

Trace the static variable num through each call to r(), remembering that post-decrement returns the current value before decrementing. Evaluate the for-loop parts in C order: initialization once, condition before each iteration, body when condition is true, then increment expression.

Post-decrement returns the old value and then decrements the static variable. Tracing the for-loop: r() before the loop returns 7 and leaves num=6; the first condition returns 6 and leaves num=5, so the body prints 5; the increment returns 4 and leaves num=3; the second condition returns 3 and leaves num=2, so the body prints 2; the next increment returns 1 and leaves num=0; the final condition returns 0 and terminates the loop. Hence the displayed value is 52.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.