Question

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?

Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2024 answer key

Solution

Evaluate the arguments h(20) then g(10) from right to left before executing the body of f(10, 20).

  1. In main(), the call f(g(10), h(20)) evaluates its arguments from right to left:
    • First, h(20) is called: it prints 20 and returns 20.
    • Second, g(10) is called: it prints 10 and returns 10.
  2. Next, f(10, 20) executes its body sequentially:
    • g(x) is called with x = 10, printing 10.
    • h(y) is called with y = 20, printing 20.

Concatenating the printed outputs gives 20101020.

Final answer

Option (A)

Common trap

Evaluating the arguments from left to right (which gives 10201020) or reversing the statements inside f.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
Question
13 of 65
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.