What will be the output of the following C program?

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a = 10, b = 20;
    swap(&a, &b);
    printf("%d %d", a, b);
    return 0;
}
                        

Options

  • A. 10 20
  • B. 20 10
  • C. 10 10
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. 20 10

Detailed Explanation

Correct Answer: 20 10

The addresses of a and b are passed to the function using &a and &b.

Inside the function, *x and *y access the actual values of a and b. Therefore, changing *x and *y changes the original variables.

Initially, a = 10 and b = 20. After swapping, a becomes 20 and b becomes 10.

Exam point: Passing addresses to a function allows the function to modify the original variables. This is commonly called passing by address using pointers.