Difference between two seperate swaps

This is a discussion on Difference between two seperate swaps within the C Programming forums, part of the General Programming Boards category; What are the advantages/disadvantages of XOR swap over using a temporary variable? I think it looks cleaner to use an ...

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

    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,714

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    612
    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, 12:24 PM
  5. seperate varibale
    By Klinerr1 in forum C++ Programming
    Replies: 3
    Last Post: 09-02-2002, 09:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21