Consider the following C function C void swap (int a, int b) { int temp; temp…
2004
Consider the following C function
C
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.
- A.
Call swap (x, y)
- B.
Call 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 value
Attempted by 388 students.
Show answer & explanation
Correct answer: D
Key point: the given swap function uses pass-by-value, so it only swaps local copies of the arguments and cannot change the caller's variables.
Pointer-based solution (typical in C): change the function to accept pointers and dereference them to swap the caller's memory.
Example:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Call with: swap(&x, &y);
Return-value solution: have the function return the swapped values (for example using a small struct) and assign them in the caller.
Example:
struct Pair { int first; int second; };
struct Pair swap(int a, int b) { struct Pair p = { b, a }; return p; }
In caller: struct Pair p = swap(x, y); x = p.first; y = p.second;
C++ reference solution: if using C++, use reference parameters so the function can directly modify the caller's variables.
Example:
void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
Call with: swap(x, y);
Conclusion: The original void swap(int a, int b) cannot exchange x and y in the caller because C passes parameters by value. Use pointers, return swapped values, or language-specific references to perform a real swap.