Thread: We can swap two numbers using Xor operator.

  1. #1
    Registered User
    Join Date
    Nov 2020

    We can swap two numbers using Xor operator.

    I was searching for how to swap two numbers without temporary variable. Then I came across this blogpost.

    He used xor operator to swap. I was amazed to see it.
    Here is his program

    int main(int argc, char const *argv[]){
        int number1,number2; 
        printf("\nSwapping of two numbers in c\nEnter two numbers\n");
        printf("Number 1: %d\nNumber 2: %d",number1,number2);
        printf("\nAfter swapping");
        printf("\nNumber 1: %d\nNumber 2: %d\n",number1,number2);
        return 0;
    Last edited by Salem; 11-05-2020 at 06:15 AM. Reason: Snipped spammy URLs

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    New York, NY
    This is a nice bar bet, but I don't know any programmer that would use this in real life.

    This can be more simplified by:
    number1 ^= number2;
    number2 ^= number1;
    number1 ^= number2;
    // Or even:
    number1 ^= number2 ^= number1 ^= number2;
    But again, I would never use it in real code.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > number1 ^= number2 ^= number1 ^= number2;
    Not really...
    Question 3.3b

    > He used xor operator to swap. I was amazed to see it.
    And if your data types are anything other than equal sized integers, you have to do it the proper way anyway.

    You hung a spoon off the end of your nose - party trick for a 5-year old.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. trying to reverse numbers with sizeof operator
    By JoelearningC in forum C Programming
    Replies: 13
    Last Post: 03-09-2008, 11:53 AM
  2. Prime Numbers, Modulus Operator Help
    By dcwang3 in forum C Programming
    Replies: 34
    Last Post: 02-07-2008, 03:16 PM
  3. using swap to make assignment operator exception safe
    By George2 in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2008, 06:32 AM

Tags for this Thread