Thread: Difference between two seperate swaps

  1. #1
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693

    Difference between two seperate swaps

    What are the advantages/disadvantages of XOR swap over using a temporary variable? I think it looks cleaner to use an XOR and also eliminates using an extra variable, however that's really not a big deal anyways with all the memory available. Why don't schools teach more about bitwise operators? Are they really that unimportant?
    Code:
    int main(void)
    {
    int x=5,y=12;
    x^=y;
    y^=x;
    x^=y;
    
    return 0;
    }
    Code:
    int main(void)
    {
    int x=5,y=12, temp;
    temp=x;
    x=y;
    y=x;
    
    return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    1. Try the xor swap within a function, using pointers to two integers.

    2. Then try and swap a variable with itself - like swap(&a,&a);

    3. Try using xor swap for other data types, like floats, doubles, pointers, structures.
    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.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Ahh, yeah I guess I was not thinking nearly enough

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seperate strings
    By ashok449 in forum C Programming
    Replies: 1
    Last Post: 10-03-2008, 06:24 AM
  2. seperate and add pos and neg numbers
    By Chris630 in forum C++ Programming
    Replies: 2
    Last Post: 03-27-2007, 06:14 PM
  3. char swaps, and echo() password masking
    By spencerhs5 in forum C Programming
    Replies: 2
    Last Post: 07-25-2006, 08:25 PM
  4. How do I seperate integers?
    By Guti14 in forum C++ Programming
    Replies: 11
    Last Post: 12-22-2003, 01:24 PM
  5. seperate varibale
    By Klinerr1 in forum C++ Programming
    Replies: 3
    Last Post: 09-02-2002, 09:56 PM