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?
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).
- In
main(), the callf(g(10), h(20))evaluates its arguments from right to left:- First,
h(20)is called: it prints20and returns20. - Second,
g(10)is called: it prints10and returns10.
- First,
- Next,
f(10, 20)executes its body sequentially:g(x)is called withx = 10, printing10.h(y)is called withy = 20, printing20.
Concatenating the printed outputs gives 20101020.
Option (A)
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.