Back to Blog

Directly Swapping Two Variable Values Without a Third Variable

#ProgrammingTechniques#VariableSwapping#BitwiseOperations#EmbeddedDevelopment

I recall seeing examples of directly swapping the values of two variables without introducing a third variable. The two methods I've encountered are as follows:

Method One:

var a=1;

var b=2;

a=a+b;

b=a-b;

a=a-b;

Printing a and b will show that their values have been swapped.

 

Method Two:

var a=1;

var b=2;

a=a^b;

b=a^b;

a=a^b;

Printing a and b will show that their values have been swapped.

   

On the surface, these two methods might seem like mere tricks or clever maneuvers. However, they play a significant role in embedded development. In embedded systems, space is limited, and the fewer variables introduced, the more space is saved, thereby increasing the available development space. Thus, these techniques are quite commonly used.

 

A brief analysis of the two methods is as follows:

Method One demonstrates a relatively clearer logical thought process, making it easier to understand. Method Two is comparatively faster because it directly utilizes bitwise operations, giving it a slight advantage in execution time.

 

From a mathematical perspective, both techniques implicitly contain the mathematical idea of set theory. In Method One, you can think of a+b as a larger set. Subtracting one of the original variables from this sum leaves the other variable as the difference set. Similarly, subtracting the other variable from a+b achieves the swapping of their values. For Method Two, since it uses the mathematical XOR operation, repeated application yields the desired effect.

 

Based on the above analysis, it's clear that many development techniques can originate from mathematical theories. Such applications rooted in mathematical theory can lead to numerous innovations in technical development and hold practical significance in real-world applications. Although the method of "swapping two variable values directly without a third variable" wasn't my invention, I believe that with a strong mathematical theoretical background, and by cultivating an awareness of such applications in development and other creative work, we too can devise such "tricks." As long as we are good at thinking and summarizing, creative thinking can indeed be nurtured.