Thread: switch memory locs with 2 lines of code

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    3

    switch memory locs with 2 lines of code

    Someone asked me how I could switch two memory locations in two lines of code.... Anyone know the answer to this trivia?

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Most likely with the evil XOR trick (although that works with one line). Don't bother.

    Of course, it depends on how you define a line.
    Code:
    inline void swapmem(void* m1, void* m2, size_t sz) { std::vector<char> buf(sz);
      memcpy(&buf[0], m1, sz); memmove(m1, m2, sz); memcpy(m2, &buf[0], sz); }
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    3

    xor trick

    Is that just

    int a = 1
    int b = 2

    a ^= b
    b ^= a

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Not quite -- I think you need
    Code:
    a ^= b;
    b ^= a;
    a ^= b;
    or
    Code:
    x ^= y ^= x ^= y;
    But note CornedBee's operative word: evil.
    Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster.[2] As a general rule, you should never use the XOR swap unless you know for a fact that the naive swap will not suit your application (which is very rare in this day and age). The XOR swap is also much less readable, and can be completely opaque to anyone who isn't already familiar with the technique.

    On modern (desktop) CPUs, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute commands in parallel; see Instruction pipeline. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture.
    From http://en.wikipedia.org/wiki/XOR_swap_algorithm

    Also see http://everything2.com/title/xor&#37;2520swap (for the one-line version)

    [edit] Really, you had it right the first time. It's just trivia. Don't use it in your code. [/edit]
    Last edited by dwks; 09-19-2008 at 05:14 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    3
    ah thats great thanks!!!

  6. #6
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    1 line:
    Code:
    std::swap( p1, p2 );
    But I'd have to think a while about how to do it in 2 lines.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by saltzmanjoelh View Post
    Someone asked me how I could switch two memory locations in two lines of code.... Anyone know the answer to this trivia?
    As a note: The number of lines in C or C++ is a pretty poor measure of how much code something produces, since you can easily write several statements on one line, or space a single statement onto many lines.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I think by "lines" they're talking about statements ending with a semicolon, rather than actual lines ending with CRLF. That's how I measure "lines of code".
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by dwks View Post
    Not quite -- I think you need
    Code:
    a ^= b;
    b ^= a;
    a ^= b;
    or
    Code:
    x ^= y ^= x ^= y;
    But note CornedBee's operative word: evil.

    From http://en.wikipedia.org/wiki/XOR_swap_algorithm

    Also see http://everything2.com/title/xor&#37;2520swap (for the one-line version)

    [edit] Really, you had it right the first time. It's just trivia. Don't use it in your code. [/edit]
    It's
    Code:
    if(a!=b){
      a ^= b;
      b ^= a;
      a ^= b;
    }
    which can be condensed to:
    Code:
    if(a!=b){
      b ^= a ^= b;
      a ^= b;
    }
    Which by cpjust's stated definition is two lines.
    Or you can do
    Code:
    a!=b?(b ^= a ^= b,a ^= b):b;
    But now it's bad style, unlike the other examples.

    You do need the check for if a == b, otherwise it will zero both values out.
    And you need the sequence points to keep things well defined.
    Last edited by King Mir; 09-20-2008 at 12:21 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    It must be &a != &b, because the problem exists when the two arguments alias each other, not when they have the same value.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Code:
    namespace 
    {
      template <class T> void swap (T & a, T & b)
      {
        T temp = a;
        a = b, b = temp;
      }
    }

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    hmm... but then what we are doing is swapping the values between two memory locations. Actually switching/swapping two memory locations... can only be done by changing the hardware?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Depends on what you mean by memory locations. You could perhaps change the address mapping in the kernel.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Line Counting
    By 00Sven in forum C Programming
    Replies: 26
    Last Post: 04-02-2006, 08:59 PM
  2. Finding number of lines of code
    By arron in forum Linux Programming
    Replies: 8
    Last Post: 01-06-2006, 05:35 AM
  3. Source code for B-Tree in main memory
    By neolyn in forum C++ Programming
    Replies: 2
    Last Post: 12-05-2004, 11:07 PM
  4. Lines from Unix's source code have been copied into the heart of Linux????
    By zahid in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 05-19-2003, 03:50 PM
  5. True ASM vs. Fake ASM ????
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 04-02-2003, 04:28 AM