GATE | GATE IT 2006 | Question 50

• Difficulty Level : Hard
• Last Updated : 28 Jun, 2021

Which one of the choices given below would be printed when the following program is executed?

 #includevoid swap (int *x, int *y){    static int *temp;    temp = x;    x = y;    y = temp;}void printab (){    static int i, a = -3, b = -6;    i = 0;    while (i <= 4)    {        if ((i++)%2 == 1) continue;        a = a + i;        b = b + i;    }    swap (&a, &b);    printf("a =  %d, b = %d\n", a, b);}main(){    printab();    printab();}

(A) a = 0, b = 3
a = 0, b = 3
(B) a = 3, b = 0
a = 12, b = 9
(C) a = 3, b = 6
a = 3, b = 6
(D) a = 6, b = 3
a = 15, b = 12

Explanation:

Things to ponder:

swap function doesn’t actually swaps two variables, rather just swaps their addresses in local variables x and y – which is effectively nothing once swap function returns.

printab function adds 9 to static variables a and b. The number 9 comes from the fact that the while loop executes those arithmetic statements only when i = 1, 3, 5.

Hence, when printab is called for the first time, these are the local variable values: a = −3 + 9 and b = −6 + 9. On the second time, a = −3 + 9 + 9 and b = −6 + 9 + 9 are the desired values.
Therefore, correct answer would be (D) a = 6, b = 3; a = 15, b = 12.

This solution is contributed by vineet purswani .

Quiz of this Question

My Personal Notes arrow_drop_up