ISRO Scientist/Engineer CSE 2017Compiler Design › Code Optimization and Runtime Environment
ISRO Scientist/Engineer CSE 2017 PYQ: Consider the following function void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } In order to…
Consider the following function
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
} In order to exchange the values of two variables $x$ and $y$.
- Acall $swap(x, y)$
- Bcall $swap(\&x, \&y)$
- C$swap (x, y)$ cannot be used as it does not return any value
- D$swap (x, y)$ cannot be used as the parameters are passed by valueCorrect answer
Answer
(D) $swap (x, y)$ cannot be used as the parameters are passed by value
Approach
The function swap takes its two parameters by value, so any changes made to a and b inside the function affect only local copies. To exchange the caller's variables, the function would need to receive their addresses (pointers) and dereference them. Since the given prototype uses plain int parameters, calling swap(x, y) cannot swap x and y.
Reviewed by ISRO IQ Editorial Team.