How to swap two variables?
The question may look silly, neither geeky. See the following piece of code to swap two integers (XOR swapping),
void myswap(int *x, int *y)
{
if (x != y)
{
*x^=*y^=*x^=*y;
}
}
At first glance, we may think nothing wrong with the code. However, when prompted for reason behind opting for XOR swap logic, the person was clue less. Perhaps any commutative operation can fulfill the need with some corner cases.
Avoid using fancy code snippets in production software. They create runtime surprises. We can observe the following notes on above code
- The code behavior is undefined. The statement *x^=*y^=*x^=*y; modifying a variable more than once in without any sequence point.
- It creates pipeline stalls when executed on a processor with pipeline architecture.
- The compiler can’t take advantage in optimizing the swapping operation. Some processors will provide single instruction to swap two variables. When we opted for standard library functions, there are more chances that the library would have been optimized. Even the compiler can recognize such standard function and generates optimum code.
- Code readability is poor. It is very much important to write maintainable code.
Thanks to Venki for writing the above article. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- Parameter Passing Techniques in C/C++
- Number of ways to change the XOR of two numbers by swapping the bits
- Swapping of subranges from different containers in C++
- Count number of unique Triangles using STL | Set 1 (Using set)
- set::begin() and set::end() in C++ STL
- C++ Internals | Default Constructors | Set 1
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Output of C++ Program | Set 10
- Exception handling and object destruction | Set 1
- XOR of all subarray XORs | Set 2
- Output of C++ Program | Set 14
- Output of C++ Program | Set 16
- Output of C++ Program | Set 18
- How to count set bits in a floating point number in C?
- Given a set, find XOR of the XOR's of all subsets.
- Find the maximum subset XOR of a given set
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- Namespace in C++ | Set 1 (Introduction)
- Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)

