Thread: Swap function using no temp variable

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    1

    Swap function using no temp variable

    i was assigned in my programming class to make a function of the form int swap(&a, &b) that doesnt use a third variable in the swap. i have pondered on this for a few hours and i cant think of anything. any help would appreciated. thanks in advance

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can do this using bit manipulation, XOR-ing the values. I've
    never needed to do this, but I believe it's something like:

    a^=b;
    b^=a;
    a^=b;

    Something like that.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Something like that.
    Yea, it's a common trick. There's no way to use it correctly, despite what some will tell you. Use a temporary variable, is it really that much harder?

    Bad Practice:
    a^=b;
    b^=a;
    a^=b;

    Good Practice
    temp = a;
    a = b;
    b = temp;

    Seems just as easy to me, and you don't suffer scary code syndrome.

    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    12
    yeah I've seen this way, but it doesn't always work..
    a^=b^=a^=b;


    here's another way (simply mathematical)

    a += b;
    b = a - b;
    a -= b;

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >yeah I've seen this way, but it doesn't always work..
    >a^=b^=a^=b;
    Of course not, the value of each variable is modified more than once between sequence points, which results in undefined behavior.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  3. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. linked list recursive function spaghetti
    By ... in forum C++ Programming
    Replies: 4
    Last Post: 09-02-2003, 02:53 PM