GATE | GATE IT 2006 | Question 50

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

filter_none

edit
close

play_arrow

link
brightness_4
code

#include
void 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();

chevron_right


(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


Answer: (D)

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
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.