References

Swapping Values Using References

How can I use references to swap the values of two variables without using a temporary variable?

3D character art

Swapping values using references without a temporary variable is a neat trick in C++. It's not only efficient but also demonstrates the power of references. Here's how you can do it:

#include <iostream>

void swap(int& a, int& b) {
  a = a + b;
  b = a - b;  // b is now original a
  a = a - b;  // a is now original b
}

int main() {
  int x{5};
  int y{10};

  std::cout << "Before swap: x = "
    << x << ", y = " << y << '\n';
  swap(x, y);
  std::cout << "After swap:  x = "
    << x << ", y = " << y << '\n';
}
Before swap: x = 5, y = 10
After swap:  x = 10, y = 5

Let's break down how this works.

First, we define a swap() function that takes two integer references as parameters.

Then, inside swap(), we perform three operations:

  • Add b to a, storing the result in a.
  • Subtract the new b from a, which gives us the original value of a, and store it in b.
  • Subtract the new b from a, which gives us the original value of b, and store it in a.

This method works because we're using references, so we're directly manipulating the original variables, not copies.

While this method is clever, it's worth noting that it can cause issues with overflow for very large numbers. In practice, the standard library's std::swap() function is often a better choice:

#include <iostream>
#include <utility>

int main() {
  int x{5};
  int y{10};

  std::cout << "Before swap: x = "
    << x << ", y = " << y << '\n';
  std::swap(x, y);
  std::cout << "After swap:  x = "
    << x << ", y = " << y << '\n';
}

std::swap() is more versatile as it works with any type, not just integers, and it handles potential edge cases more robustly.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

View Course
Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved