LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 1

Swap by value vs swap by reference Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

What is the output of the following C++ program?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links