VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-two-variables-in-one-line-in-c-c-python-php-and-java/

⇱ Swap Two Variables in One Line - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap Two Variables in One Line

Last Updated : 23 Jul, 2025

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]

Output

After Swapping values of x and y are 10 5

Alternate Solutions: 

  1. Using swap(): C++ library function
  2. b = (a + b) - (a = b);
  3. a += b - (b = a);
  4. a = a * b / (b = a)
  5. a = a ^ b ^ (b = a)

Time complexity : O(1) 
Auxiliary Space : O(1)

Comment
Article Tags:
Article Tags: