
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Two Variables in One Line in C/C++
In C++, swapping two variables means exchanging the values stored in them. There can be multiple ways to implement the swapping using single line statement. In this article, we are going to learn some of the approaches to swap the values.
Example
Let's consider the following example with input and output scenario:
Input: int a = 5; int b = 6; Output: a = 6 b = 5
You can implement swapping of two variable by using the following different ways:
Swap Two Variables Using Arithmetic Operator
In C++, swapping variables using arithmetic operations is possible without temporary storage. The arithmetic operator only works with numeric types.
Example
This is the basic C++ program to swap two variables in one line using an arithmetic operator:
#include <iostream> using namespace std; int main() { int a = 5, b = 10; a = (a + b) - (b = a); cout << "a: " << a << ", b: " << b; return 0; }
The above program produces the following output:
a: 10, b: 5
Swap Two Variables Using Tuple
Two variables can also be swapped using the tuples. You need to declare two variables (a and b) and assign the values (5, 10) and then use tie(a, b) = make_tuple(b, a); which creates a tuple with the values (b, a) and assigns them back to a and b respectively. This statement will swap their values. As a result, a becomes 10 and b becomes 5, and the output of the program is: a: 10, b: 5.
Example
In this example, use a C++ program to swap two variables in one line of code using a tuple:
#include <iostream> #include <tuple> using namespace std; int main() { int a = 5, b = 10; tie(a, b) = make_tuple(b, a); cout << "a: " << a << ", b: " << b; return 0; }
The above program produces the following output:
a: 10, b: 5
Swap Two Variables Using XOR
In this approach, swap variables using a bitwise XOR operation. This only works with integer types.
Following are the steps:
- First, declare two variables a and b, and assign the values 5 and 10 to them.
- Use a single line a ^= b ^= a ^= b; to swap the values of a and b using the bitwise XOR operation.
- This line performs a swap without using a temporary variable.
- Print the values of a and b after swapping.
Example
Following is the C++ program to swap two variables in one line using XOR:
#include <iostream> using namespace std; int main() { int a = 5, b = 10; a ^= b ^= a ^= b; cout << "a: " << a << ", b: " << b; return 0; }
The above program produces the following output:
a: 10, b: 5