devxlogo

Another Technique for Swapping Two Integers Without Using a Temporary

Another Technique for Swapping Two Integers Without Using a Temporary

In a previous tip, I showed how to swap two variables without using a temporary variable. There’s another version of this solution that applies to integral values only. Here it is:

 void swap(int& i, int& j){ i ^= j; j ^= i; i ^= j;}// i and j are swapped

You can apply this technique to any integral type, e.g., char, short, unsigned long, but not to floating-point variables.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist