Consider the C program below. What does it print? C # include <stdio.h> #…

2008

Consider the C program below. What does it print?

C

# include <stdio.h>
# define swapl (a, b) tmp = a; a = b; b = tmp
void swap2 ( int a, int b)
{
        int tmp;
        tmp = a; a = b; b = tmp;
 }
void swap3 (int*a, int*b)
{
        int tmp;
        tmp = *a; *a = *b; *b = tmp;
}
int main ()
{
        int num1 = 5, num2 = 4, tmp;
        if (num1 < num2) {swap1 (num1, num2);}
        if (num1 < num2) {swap2 (num1 + 1, num2);}
        if (num1 >= num2) {swap3 (&num1, &num2);}
        printf ("%d, %d", num1, num2);
}
 /* Add code here. Remove these lines if not writing code */ 

  1. A.

    5, 5

  2. B.

    5, 4

  3. C.

    4, 5

  4. D.

    4, 4

Attempted by 111 students.

Show answer & explanation

Correct answer: C

Answer: 4, 5

Explanation:

  • Initial values: num1 = 5, num2 = 4.

  • First conditional (num1 < num2) is false (5 < 4 is false), so the first swap is not executed.

  • Second conditional (num1 < num2) is also false, so the function that would receive values by value is not executed. Even if it ran, passing by value would not change the caller's variables.

  • Third conditional (num1 >= num2) is true (5 >= 4), so the function that receives pointers is called with the addresses of num1 and num2. That function swaps the values through dereferencing, so num1 becomes 4 and num2 becomes 5.

  • Finally, printf prints the updated values: 4, 5.

Key point: swapping by value (pass-by-value) does not change the caller's variables; swapping via pointers (pass-by-reference style) does.

Explore the full course: Gate Guidance By Sanchit Sir