Pointers

Swapping Values with Pointers

How can I use pointers to efficiently swap two values without using a temporary variable?

3D character art

Swapping values using pointers without a temporary variable is an interesting technique, but it's important to note that it's not always the most readable or maintainable approach. However, it can be useful in certain situations where performance is critical. Here's how you can do it:

#include <iostream>

void swap(int* a, int* b) {
  // Check if the pointers are not the same
  if (a != b) {
    // XOR the values
    *a = *a ^ *b;
    // XOR again to get the original value of a
    *b = *a ^ *b;
    // XOR one more time to get the
    // original value of b
    *a = *a ^ *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

This technique uses the XOR operation to swap the values. Here's how it works:

  1. a = *a ^ *b: This XORs the values of a and b and stores the result in a.
  2. b = *a ^ *b: This XORs the new value of a with b, which gives us the original value of a, stored in b.
  3. a = *a ^ *b: This XORs the value in a with the new value in b, giving us the original value of b, now stored in a.

While this method is clever, it's worth noting that modern compilers are very good at optimizing standard swap operations. In most cases, using a temporary variable or std::swap() will be just as efficient and much more readable:

#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";
}

Remember, code readability is often more important than micro-optimizations. Use the pointer-based swap only when you have a specific reason to do so and when you're sure it provides a significant performance benefit in your specific use case.

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