Click here to Skip to main content
15,886,963 members
Articles / Programming Languages / C++/CLI
Article

The Stupid XOR Trick

Rate me:
Please Sign up or sign in to vote.
3.58/5 (28 votes)
13 Aug 2002CPOL2 min read 248.3K   39   130
Explaining the phenomenon of x^=y^=x^=y;

Introduction

As a result of many, sometimes insulting, reactions on my signature, I decided to write an article on this topic. The mentioned signature looks like this:

int x=1, y=5; 
x^=y^=x^=y; // what's the content of x and y now?

Well, the reactions range from "that's not even valid C/C++ code" to "that works only with X=1 and y=5" and "you better learn C". To all these unbelievers and of course everyone else who doesn't know this "trick"; may this article enlighten you :)

What it's meant to do

Simply exchange the values of two integer variables without using a temporary variable. It gives unpredictable results with other variable types than integer types.

The symbol ^ is the XOR operator used in C/C++. See the article from PJ Arends on Bitwise Operators for a full introduction to bits and related operators.

The questionable code fragment x^=y^=x^=y; can be expanded into x XOR y XOR x XOR y. Since C/C++ resolves expressions like this from right to left, we can split it into the steps performed by the compiler:

x ^= y; // the right-most expression
y ^= x; // the middle expression
x ^= y; // the left-most expression

Which can be further expanded into

x = x ^ y; // x = 1 XOR 5  -> x = 4
y = y ^ x; // y = 5 XOR 4 = 1  -> y = 1
x = x ^ y; // x = 4 XOR 1 = 5  -> x = 5

Voila, here we are x=5 and y=1. That's what we wanted to achieve. And all this without using a temporary variable like in int t = x; x = y; y = t; which most programmers use. I confess that my method is confusing to most people because it's a little known method. As an additional benefit, the compiler can translate it into 3 simple XOR assembler statements.

Sample

For all who still don't believe it, here is a sample program to prove  that it works (with any integer number). The sample can be compiled in Ansi and Unicode and is compatible with VC6 and VC7. It is not using any library except the standard C Runtime Library.

#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>

int _tmain(int argc, TCHAR* argv[])
{
    if(argc != 3)
    {
        _tprintf(
            _T("\nUsage: StupidXORTricks.exe intvalue1 intvalue2\n"));
    }
    else
    {
        int x = _ttoi(argv[1]);
        int y = _ttoi(argv[2]);

        _tprintf(_T("x = %d, y = %d\n"), x, y);
        _tprintf(_T("Performing x^=y^=x^=y...\n"));
		
        x^=y^=x^=y;

        _tprintf(_T("x = %d, y = %d\n"), x, y);

    }
    return 0;
}

Finally, I hope that I don't get any more responses to my sig. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Portugal Portugal
Software Smith, Blacksmith, Repeat Founder, Austrian, Asgardian.

Comments and Discussions

 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
.:floyd:.14-Jun-03 0:23
.:floyd:.14-Jun-03 0:23 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
Anonymous2-Nov-03 21:29
Anonymous2-Nov-03 21:29 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
BSCE200620-Nov-04 22:49
BSCE200620-Nov-04 22:49 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
bitznarf9-Aug-06 7:35
bitznarf9-Aug-06 7:35 
GeneralSuprised Pin
John R. Shaw4-May-03 11:13
John R. Shaw4-May-03 11:13 
GeneralThanks... Pin
Xambo11-Apr-03 19:52
Xambo11-Apr-03 19:52 
GeneralA trick known ... Pin
AquaRegia26-Aug-02 23:11
AquaRegia26-Aug-02 23:11 
GeneralRe: A trick known ... as undefined behaviour Pin
Moak21-Nov-02 4:01
Moak21-Nov-02 4:01 
GeneralRe: A trick known ... as undefined behaviour Pin
.:floyd:.26-Jun-03 9:00
.:floyd:.26-Jun-03 9:00 
GeneralRe: A trick known ... Pin
Dimitris Vasiliadis26-Sep-03 22:59
Dimitris Vasiliadis26-Sep-03 22:59 
GeneralNice little trick Pin
Brian Delahunty26-Aug-02 1:26
Brian Delahunty26-Aug-02 1:26 
GeneralRe: Nice little trick Pin
Andreas Saurwein26-Aug-02 10:18
Andreas Saurwein26-Aug-02 10:18 
GeneralSuch XOR swap not work with : int * y = &x; Pin
Sprinter19-Aug-02 22:08
Sprinter19-Aug-02 22:08 
GeneralRe: Such XOR swap not work with : int * y = &x; Pin
Crius20-Aug-02 5:58
Crius20-Aug-02 5:58 
GeneralDangerous to use with pointers on common array Pin
Sprinter20-Aug-02 22:28
Sprinter20-Aug-02 22:28 
GeneralRe: Dangerous to use with pointers on common array Pin
Crius21-Aug-02 4:55
Crius21-Aug-02 4:55 
GeneralRe: Dangerous to use with pointers on common array Pin
Anonymous9-May-03 11:26
Anonymous9-May-03 11:26 
GeneralRe: Dangerous to use with pointers on common array Pin
Crius9-May-03 11:39
Crius9-May-03 11:39 
GeneralRe: Such XOR swap not work with : int * y = &x; Pin
Andreas Saurwein26-Aug-02 10:24
Andreas Saurwein26-Aug-02 10:24 
GeneralAlternative Way Pin
Krishnendu sengupta19-Aug-02 20:52
Krishnendu sengupta19-Aug-02 20:52 
GeneralRe: Alternative Way Pin
Jack Ploeg19-Aug-02 22:38
Jack Ploeg19-Aug-02 22:38 
GeneralRe: Alternative Way Pin
Krishnendu sengupta20-Aug-02 0:22
Krishnendu sengupta20-Aug-02 0:22 
GeneralRe: Alternative Way Pin
AntonGogolev31-Oct-02 21:56
AntonGogolev31-Oct-02 21:56 
GeneralRe: Alternative Way Pin
vboctor6-Nov-02 18:18
vboctor6-Nov-02 18:18 
GeneralRe: Alternative Way Pin
Dimitris Vasiliadis26-Sep-03 23:13
Dimitris Vasiliadis26-Sep-03 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.