Click here to Skip to main content
11,581,982 members (74,680 online)
Click here to Skip to main content

The Stupid XOR Trick

, 13 Aug 2002 CPOL 196.6K 39
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

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. Smile | :)

License

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

Share

About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
.:floyd:.23-Feb-14 1:27
member.:floyd:.23-Feb-14 1:27 
GeneralRe: My vote of 1 Pin
Andreas S. Franci Gonçalves23-Feb-14 4:08
professionalAndreas S. Franci Gonçalves23-Feb-14 4:08 
GeneralRe: My vote of 1 Pin
.:floyd:.23-Feb-14 12:21
member.:floyd:.23-Feb-14 12:21 
GeneralSee this. Pin
Nibu thomas7-Nov-05 17:27
memberNibu thomas7-Nov-05 17:27 
GeneralRe: See this. Pin
toxcct26-Feb-06 23:42
membertoxcct26-Feb-06 23:42 
GeneralRe: See this. Pin
Nibu thomas26-Feb-06 23:43
memberNibu thomas26-Feb-06 23:43 
GeneralRe: See this. Pin
toxcct26-Feb-06 23:45
membertoxcct26-Feb-06 23:45 
GeneralRe: See this. Pin
Nibu thomas26-Feb-06 23:48
memberNibu thomas26-Feb-06 23:48 
GeneralRe: See this. Pin
toxcct26-Feb-06 23:51
membertoxcct26-Feb-06 23:51 
GeneralRe: See this. Pin
Nibu thomas26-Feb-06 23:52
memberNibu thomas26-Feb-06 23:52 
GeneralRe: See this. Pin
toxcct26-Feb-06 23:54
membertoxcct26-Feb-06 23:54 
GeneralRe: See this. Pin
Nibu thomas26-Feb-06 23:56
memberNibu thomas26-Feb-06 23:56 
GeneralTrick subject to compiler (eek, gcc 3.x) Pin
Anonymous17-Aug-05 14:18
sussAnonymous17-Aug-05 14:18 
GeneralA tiny &quot;proof&quot; for the trick, just for fun Pin
Humpzlopogas15-Nov-03 17:37
memberHumpzlopogas15-Nov-03 17:37 
GeneralRe: A tiny &quot;proof&quot; for the trick, just for fun Pin
SaurweinAndreas16-Nov-03 4:07
memberSaurweinAndreas16-Nov-03 4:07 
GeneralRe: A tiny "proof" for the trick, just for fun Pin
.:floyd:.23-Feb-14 1:14
member.:floyd:.23-Feb-14 1:14 
GeneralOld trick Pin
Dimitris Vassiliades26-Sep-03 22:56
memberDimitris Vassiliades26-Sep-03 22:56 
GeneralRe: Old trick Pin
Mr.Prakash1-Dec-03 16:43
memberMr.Prakash1-Dec-03 16:43 
GeneralRe: Old trick Pin
Dimitris Vassiliades1-Dec-03 18:56
memberDimitris Vassiliades1-Dec-03 18:56 
GeneralRe: Old trick Pin
Mr.Prakash1-Dec-03 21:16
memberMr.Prakash1-Dec-03 21:16 
Generalx ^= y ^= x ^= y is undefined. Period. Pin
stickboy20-May-03 17:57
sussstickboy20-May-03 17:57 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
SaurweinAndreas21-May-03 4:29
memberSaurweinAndreas21-May-03 4:29 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
stickboy21-May-03 17:36
sussstickboy21-May-03 17:36 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
SaurweinAndreas22-May-03 0:03
memberSaurweinAndreas22-May-03 0:03 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
stickboy22-May-03 7:11
sussstickboy22-May-03 7:11 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
.:fl0yd:.14-Jun-03 0:23
member.:fl0yd:.14-Jun-03 0:23 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
Anonymous2-Nov-03 21:29
sussAnonymous2-Nov-03 21:29 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
BSCE200620-Nov-04 22:49
memberBSCE200620-Nov-04 22:49 
GeneralRe: x ^= y ^= x ^= y is undefined. Period. Pin
bitznarf9-Aug-06 7:35
memberbitznarf9-Aug-06 7:35 
GeneralSuprised Pin
John R. Shaw4-May-03 11:13
memberJohn R. Shaw4-May-03 11:13 
GeneralThanks... Pin
Xambo11-Apr-03 19:52
sussXambo11-Apr-03 19:52 
GeneralA trick known ... Pin
AquaRegia26-Aug-02 23:11
memberAquaRegia26-Aug-02 23:11 
GeneralRe: A trick known ... as undefined behaviour Pin
Moak21-Nov-02 4:01
sussMoak21-Nov-02 4:01 
GeneralRe: A trick known ... as undefined behaviour Pin
.:fl0yd:.26-Jun-03 9:00
member.:fl0yd:.26-Jun-03 9:00 
GeneralRe: A trick known ... Pin
Dimitris Vassiliades26-Sep-03 22:59
memberDimitris Vassiliades26-Sep-03 22:59 
GeneralNice little trick Pin
Brian Delahunty26-Aug-02 1:26
editorBrian Delahunty26-Aug-02 1:26 
GeneralRe: Nice little trick Pin
Andreas Saurwein26-Aug-02 10:18
memberAndreas Saurwein26-Aug-02 10:18 
GeneralSuch XOR swap not work with : int * y = &x; Pin
Sprinter19-Aug-02 22:08
memberSprinter19-Aug-02 22:08 
GeneralRe: Such XOR swap not work with : int * y = &x; Pin
Crius20-Aug-02 5:58
memberCrius20-Aug-02 5:58 
GeneralDangerous to use with pointers on common array Pin
Sprinter20-Aug-02 22:28
memberSprinter20-Aug-02 22:28 
GeneralRe: Dangerous to use with pointers on common array Pin
Crius21-Aug-02 4:55
memberCrius21-Aug-02 4:55 
GeneralRe: Dangerous to use with pointers on common array Pin
Anonymous9-May-03 11:26
sussAnonymous9-May-03 11:26 
GeneralRe: Dangerous to use with pointers on common array Pin
Crius9-May-03 11:39
memberCrius9-May-03 11:39 
GeneralRe: Such XOR swap not work with : int * y = &x; Pin
Andreas Saurwein26-Aug-02 10:24
memberAndreas Saurwein26-Aug-02 10:24 
GeneralAlternative Way Pin
Krishnendu sengupta19-Aug-02 20:52
memberKrishnendu sengupta19-Aug-02 20:52 
GeneralRe: Alternative Way Pin
Jack Ploeg19-Aug-02 22:38
memberJack Ploeg19-Aug-02 22:38 
GeneralRe: Alternative Way Pin
Krishnendu sengupta20-Aug-02 0:22
memberKrishnendu sengupta20-Aug-02 0:22 
GeneralRe: Alternative Way Pin
Thresher31-Oct-02 21:56
memberThresher31-Oct-02 21:56 
GeneralRe: Alternative Way Pin
vboctor6-Nov-02 18:18
membervboctor6-Nov-02 18:18 
GeneralRe: Alternative Way Pin
Dimitris Vassiliades26-Sep-03 23:13
memberDimitris Vassiliades26-Sep-03 23:13 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 14 Aug 2002
Article Copyright 2002 by Andreas S. Franci Gonçalves
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid