Swap Two Variables in One Line - GeeksforGeeks

21 Jan, 2022
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.2) C/C++: Below is one generally provided classical solution: 
// Swap using bitwise XOR (Wrong Solution in C/C++)
x ^= y ^= x ^= y; 
The above solution is wrong in C/C++ as it causes undefined behavior (the compiler is free to behave in any way). The reason is, modifying a variable more than once in an expression causes undefined behavior if there is no sequence point between the modifications. However, we can use a comma to introduce sequence points. So the modified solution is 
// Swap using bitwise XOR (Correct Solution in C/C++)
// sequence point introduced using comma.
(x ^= y), (y ^= x), (x ^= y);
3) Java: In Java, rules for subexpression evaluations are clearly defined. The left-hand operand is always evaluated before the right-hand operand. In Java, the expression “x ^= y ^= x ^= y;” doesn’t produce the correct result according to Java rules. It makes x = 0. However, we can use “x = x ^ y ^ (y = x);” Note the expressions are evaluated from left to right. If x = 5 and y = 10 initially, the expression is equivalent to “x = 5 ^ 10 ^ (y = 5);”. Note that we can’t use this in C/C++ as in C/C++, it is not defined whether the left operand or right operand is executed by any operator (See this for more details).
4) JavaScript: Using destructing assignment, we can simply achieve swapping using this one line. 
[x,y]=[y,x]
C
C++
Java
Python3
C#
PHP
Javascript
// C program to swap two variables in single line#include <stdio.h>int main(){    int x = 5, y = 10;    (x ^= y), (y ^= x), (x ^= y);    printf("After Swapping values of x and y are %d %d", x,           y);    return 0;}
// C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){    int x = 5, y = 10;    // Code to swap 'x'  and 'y'    // to swap two numbers in one    // line     x = x ^ y, y = x ^ y, x = x ^ y;    // printing the swapped variables    cout << "After Swapping: x = "         << x << ", y= " << y;    return 0;}
// Java program to swap two variables in a single lineclass GFG {    public static void main(String[] args)    {        int x = 5, y = 10;        x = x ^ y ^ (y = x);        System.out.println(            "After Swapping values"            +" of x and y are " + x            + " " + y);    }}
# Python program to swap two variables in a single linex = 5y = 10x, y = y, xprint("After Swapping values of x and y are", x, y)
// C# program to swap two// variables in single lineusing System; class GFG {    static public void Main()    {        int x = 5, y = 10;        x = x ^ y ^ (y = x);        Console.WriteLine("After Swapping values "                          + "of x and y are " + x + " "                          + y);    }} // This code is contributed by aj_36
<?php// PHP program to swap two// variables in single line     // Driver Code    $x = 5;    $y = 10;    ($x ^= $y);    ($y ^= $x);    ($x ^= $y);    echo "After Swapping values of x and y are "                                  ,$x," ", $y; // This code is contributed by Vishal Tripathi?>
<script>// javascript program to swap two variables in single line     let x = 5, y = 10;    (x ^= y), (y ^= x), (x ^= y);    document.write("After Swapping values of x and y are ", x + " ",           y);  // This code is contributed by Surbhi Tyagi</script>
Output
After Swapping values of x and y are 10 5
Alternate Solutions: 
Using swap(): C++ library functionb = (a + b) – (a = b);a += b – (b = a);a = a * b / (b = a)a = a ^ b ^ (b = a)
Using swap(): C++ library function
b = (a + b) – (a = b);
a += b – (b = a);
a = a * b / (b = a)
a = a ^ b ^ (b = a)
This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
kongasricharan
bunnyram19
surbhityagi15
itshimanshu
CoderSaty
anshikajain26
amartyaghoshgfg
Bitwise-XOR
C Language
C++
Java
Python
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects