IAE Academy

GATE 2024 CS2 Q.13: solution and answer

GATE 2024 · CS2Q.13 · 1 mark · MCQ

Consider the following C program. Assume parameters to a function are evaluated from right to left.

#include <stdio.h>

int g(int p) { printf("%d", p); return p; }
int h(int q) { printf("%d", q); return q; }

void f(int x, int y) {
  g(x);
  h(y);
}

int main() {
  f(g(10),h(20));
}

Which one of the following options is the CORRECT output of the above C program?

  1. (A)

    20101020

  2. (B)

    10202010

  3. (C)

    20102010

  4. (D)

    10201020

See the question in the paper

Answer and solution

ANSWER

The correct output of the program is 20101020, which is option (A).

Official answer: ASource: Official answer key, GATE 2024 CS2 (IISc Bengaluru)

  1. main() calls f(g(10), h(20)). Since the arguments to f are evaluated right to left, h(20) is evaluated before g(10).

  2. h(20) runs first: printf("%d", q) with q = 20 prints 20, and the call returns 20.

  3. g(10) runs next: printf("%d", p) with p = 10 prints 10, and the call returns 10.

  4. Output so far (from evaluating the arguments): 2010.

  5. Now f(x, y) executes with its parameters bound by position: x receives the return value of g(10), i.e. x = 10; y receives the return value of h(20), i.e. y = 20. The order in which the arguments were evaluated does not change which parameter each one is bound to.

  6. Inside f: the statement g(x) calls g(10), printing 10 (its return value is discarded).

  7. Next, h(y) calls h(20), printing 20 (its return value is discarded).

  8. Output added by the body of f: 1020.

  9. Concatenating everything printed, in order: 2010 + 1020 = 20101020, which is option (A).

KEY IDEA

Separate two independent things: (1) the order in which argument expressions are evaluated (right to left here, which only affects the order of side-effect printing during the call f(g(10), h(20))), and (2) which value ends up bound to which parameter inside the called function (always by position — the first argument's value goes to the first parameter, regardless of evaluation order).

WATCH OUT FOR

Assuming that "right to left evaluation" also means the parameters are somehow bound out of order inside f, e.g. treating y as if it held g(10)'s value because h(20) was evaluated first. Evaluation order only changes when the side effects (the printf calls inside g and h as arguments) happen; it never changes that the first written argument's value goes to the first parameter (x) and the second to the second (y).

From the GATE 2024 CS2 paper. Every question of this paper · Download the full paper · All 7 Functions & scope questions, with notes

More Functions & scope questions