Consider the following C program. Assume parameters to a function are…

2024

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

Attempted by 122 students.

Show answer & explanation

Correct answer: A

Concept

In C, the order in which a function's argument expressions are evaluated is unspecified by the standard; a compiler may pick any order. This problem fixes that order: the argument expressions of a call are evaluated right to left. Each call to g or h prints its value at the moment it executes, so the printed sequence is exactly the order in which the calls fire.

Application — trace the calls in firing order

Start at f(g(10), h(20)). Its two argument expressions are evaluated right to left before f runs, then f's body runs top to bottom.

  1. h(20) is the right argument, so it fires first: it prints 20 and returns 20.

  2. g(10) is the left argument, fires next: it prints 10 and returns 10.

  3. With both arguments evaluated, f(10, 20) is invoked. Inside f, g(x) runs first and prints 10.

  4. Then h(y) runs and prints 20.

Cross-check

Reading the four prints in firing order gives 20, 10, 10, 20. Concatenated with no separators (each printf uses "%d"), the program writes 20101020. Note the symmetry: argument evaluation contributes "20 10" (right-to-left), and f's body contributes "10 20" (the parameters x, y in declaration order), so the two halves are mirror images.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir