Click here to Skip to main content
15,888,454 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.4K   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: It's an interview question! Pin
Anonymous23-Aug-02 9:26
Anonymous23-Aug-02 9:26 
GeneralRe: It's an interview question! Pin
Anonymous23-Aug-02 9:31
Anonymous23-Aug-02 9:31 
GeneralRe: It's an interview question! Pin
Alex Panov24-Aug-02 22:00
Alex Panov24-Aug-02 22:00 
GeneralRe: It's an interview question! Pin
Philippe Mori28-Aug-02 3:19
Philippe Mori28-Aug-02 3:19 
GeneralRe: It's an interview question! Pin
rolst522-Nov-02 3:08
rolst522-Nov-02 3:08 
GeneralRe: It's an interview question! (one answer) Pin
Alton Williams19-Oct-03 2:18
Alton Williams19-Oct-03 2:18 
GeneralRe: It's an interview question! Pin
Zyxil26-Aug-02 2:36
Zyxil26-Aug-02 2:36 
GeneralRe: It's an interview question! Pin
Tim Lesher26-Aug-02 5:34
Tim Lesher26-Aug-02 5:34 
There's no assumption that this is a line of code from their working product sources!

It's just an exercise in problem solving--no more, no less.

Personally, I can see asking this in the interview. I don't care as much about whether they get the answer as I do about how they try to work out the solution.

Even your answer, "If that stupid piece of code is not documented, then I don't want to work here," is a good one; I would follow that up by saying "Good judgement on your part. Of course we don't actually code like this in production, but can you figure out what this should do?"

If they force you to do puzzle tricks, then that is how they code: no documentation, and a focus on minutia.

That's an amazing leap of logic. That's like saying that if someone ever makes a typo in a post on CodeProject, then they must have subtle bugs in their code resulting from typos.

Tim Lesher <tim@lesher.ws>
http://www.lesher.ws
QuestionEh? Pin
-Dy15-Aug-02 0:16
-Dy15-Aug-02 0:16 
AnswerRe: Eh? Pin
S van Leent15-Aug-02 3:11
S van Leent15-Aug-02 3:11 
GeneralOMG I can't belive I read this article Pin
lex_cdn14-Aug-02 22:00
lex_cdn14-Aug-02 22:00 
GeneralRe: OMG I can't belive I read this article Pin
Andreas Saurwein16-Aug-02 6:36
Andreas Saurwein16-Aug-02 6:36 
Generalold trick Pin
Peter Marino14-Aug-02 20:04
Peter Marino14-Aug-02 20:04 
GeneralPlain evil Pin
Robin14-Aug-02 18:23
Robin14-Aug-02 18:23 
QuestionWas it me ? Pin
ColinDavies14-Aug-02 17:58
ColinDavies14-Aug-02 17:58 
AnswerRe: Was it me ? Pin
Andreas Saurwein16-Aug-02 6:32
Andreas Saurwein16-Aug-02 6:32 
GeneralNice trick Pin
Nish Nishant14-Aug-02 17:47
sitebuilderNish Nishant14-Aug-02 17:47 
GeneralRe: Nice trick Pin
ColinDavies14-Aug-02 18:05
ColinDavies14-Aug-02 18:05 
GeneralRe: Nice trick Pin
Nish Nishant14-Aug-02 18:17
sitebuilderNish Nishant14-Aug-02 18:17 
GeneralRe: Nice trick Pin
ColinDavies14-Aug-02 18:22
ColinDavies14-Aug-02 18:22 
GeneralPoor maintenance programmers Pin
Bugra Barin14-Aug-02 13:27
Bugra Barin14-Aug-02 13:27 
GeneralRe: Poor maintenance programmers Pin
ColinDavies14-Aug-02 18:11
ColinDavies14-Aug-02 18:11 
GeneralRe: Poor maintenance programmers Pin
Anonymous15-Aug-02 3:00
Anonymous15-Aug-02 3:00 
GeneralRe: Poor maintenance programmers Pin
Andreas Saurwein16-Aug-02 6:30
Andreas Saurwein16-Aug-02 6:30 
GeneralRe: Poor maintenance programmers Pin
Jens Doose20-Aug-02 0:52
Jens Doose20-Aug-02 0:52 

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.