GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 2

Pass-by-value swap

Programming in C · Functions & Parameter Passing · Full GATE CSE 2004 paper

GATE 2004, Q2 1 mark · MCQ
Report issue

Functions & Parameter Passing

Question 2, GATE 2004: Consider this C function:
void swap(int a, int b) {
  int temp; temp = a; a = b; b = temp;
}
To exchange caller variables x and y, which statement is correct?
Options:
(A) Call swap(x,y)
(B) Call swap(&x,&y)
(C) swap(x,y) cannot be used because it returns no value
(D) swap(x,y) cannot be used because its parameters are passed by value
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. The function receives local copies a and b. Swapping those copies does not modify the caller’s x,y, so D.

2. A void function can modify caller objects through pointers, but this function’s parameters are int, not int*, and calling it with addresses does not repair its body.

3. Teaching check: Trace x=3,y=8: entry makes local a=3,b=8; the body leaves a=8,b=3, but x=3,y=8. A correct pointer-based version would take int *a,int *b and exchange *a,*b. A return value is not essential for that alternative.

Original paper, page 1