C++ swap

Introduction

Swap is a common programming task. It is used to exchange the values of two variables.
In C++, you can swap two variables using a temporary variable or without using a temporary variable.
In this tutorial, we will learn how to swap two variables using both methods.

Code - Swap with temporary variable

Example:

int x = 10; int y = 20; int temp; // Before swapping, x = 10, y = 20 temp = x; // x = 10, y = 20, temp = 10 x = y; // x = 20, y = 20, temp = 10 y = temp; // x = 20, y = 10, temp = 10
After the code is executed, x will be 20 and y will be 10.

Code - Swap without temporary variable

Example:

int x = 10; int y = 20; // Before swapping, x = 10, y = 20 x = x + y; // x = 30, y = 20 y = x - y; // x = 30, y = 10 x = x - y; // x = 20, y = 10