Question 1
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
void swap_copy(int a, int b) { int t = a; a = b; b = t; }
void swap_ref(int& a, int& b) { int t = a; a = b; b = t; }
int main() {
int x = 1, y = 2;
swap_copy(x, y);
std::cout << x << y << ' ';
swap_ref(x, y);
std::cout << x << y << '\n';
return 0;
}
- A 12 21 Correct
- B 21 21
- C 21 12
- D 12 12
Correct Answer: Option A
swap_copy swaps its own copies, which are discarded. swap_ref swaps through references to x and y.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!