GATE / CS ARCHIVE

GATE CSE 2015 SET 1 / QUESTION 34

GATE CSE 2015 Set 1 Q34

Programming in C · Functions & Parameter Passing · Full GATE CSE 2015 Set 1 paper

GATE 2015 Set 1, Q34 1 mark · NAT
Report issue

Functions & Parameter Passing

Question 34, GATE 2015: Find the printed integer. C code: void f1(int a,int b){int c;c=a;a=b;b=c;} void f2(int *a,int *b){int c;c=*a;*a=*b;*b=c;} int main(){int a=4,b=5,c=6;f1(a,b);f2(&b,&c);printf("%d",c-a-b);}. Assume required declarations.
Tap to enlarge
Answer & solution

Official answer: -5

Our answer: −5

At f1 entry the parameters copy the caller's 4 and 5; swapping these copies leaves main's a,b,c at 4,5,6. In f2, the pointer parameters are also copied, but dereferencing them reaches main's b and c. Saving *a before overwriting prevents losing the original b. After the swap main has 4,6,5; subtraction is left-associative, so (5−4)−6=−5.

Solution: The value-parameter swap f1 changes only its local copies. The pointer-based f2 swaps caller b and c, giving a=4, b=6, c=5. Therefore c−a−b=−5, with routine declarations assumed.

Original paper, page 13 · Answer key