Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. swap two values withou using temp. storage

swap two values withou using temp. storage

Scheduled Pinned Locked Moved C / C++ / MFC
help
32 Posts 23 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L lgmanuel

    hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

    N Offline
    N Offline
    Nuri Ismail
    wrote on last edited by
    #4
    1. With simple arithmetic operations:

    int x = 150;
    int y = 45;
    x = x + y;
    y = x - y;
    x = x - y;

    [EDIT] The above technique is dangerous because in some situations you can exceed the data types range!! Now I know (thanks to emilio_grv and his excellent post[^]) that this technique is not dangerous if the two variables are of the same integer type. [/EDIT] 2) The XOR swap:

    int x = 150;
    int y = 45;
    x ^= y;
    y ^= x;
    x ^= y;

    You can read more about the XOR swap here[^]. Also you can check out some CodeProject articles (and their message boards) on this topic: - A Curious Economic Swap[^] - The Stupid XOR Trick[^] :)

    modified on Thursday, July 22, 2010 3:56 AM

    E A V 3 Replies Last reply
    0
    • N Nuri Ismail
      1. With simple arithmetic operations:

      int x = 150;
      int y = 45;
      x = x + y;
      y = x - y;
      x = x - y;

      [EDIT] The above technique is dangerous because in some situations you can exceed the data types range!! Now I know (thanks to emilio_grv and his excellent post[^]) that this technique is not dangerous if the two variables are of the same integer type. [/EDIT] 2) The XOR swap:

      int x = 150;
      int y = 45;
      x ^= y;
      y ^= x;
      x ^= y;

      You can read more about the XOR swap here[^]. Also you can check out some CodeProject articles (and their message boards) on this topic: - A Curious Economic Swap[^] - The Stupid XOR Trick[^] :)

      modified on Thursday, July 22, 2010 3:56 AM

      E Offline
      E Offline
      Emilio Garavaglia
      wrote on last edited by
      #5

      Point 1 isn't dangerous at all. The carry overflow of the sum is compensated by a missing borrow of the subtraction. Both +- and ^ operates on closed Galois field (+- of size 232 and ^ on 32 fields of size 2) The only difference is that the ^ operation requires a combinatorial network simpler than + and this can make the processor ALU faster. But it is quite hard this may be observed outside.

      2 bugs found. > recompile ... 65534 bugs found. :doh:

      N P 2 Replies Last reply
      0
      • E Emilio Garavaglia

        Point 1 isn't dangerous at all. The carry overflow of the sum is compensated by a missing borrow of the subtraction. Both +- and ^ operates on closed Galois field (+- of size 232 and ^ on 32 fields of size 2) The only difference is that the ^ operation requires a combinatorial network simpler than + and this can make the processor ALU faster. But it is quite hard this may be observed outside.

        2 bugs found. > recompile ... 65534 bugs found. :doh:

        N Offline
        N Offline
        Nuri Ismail
        wrote on last edited by
        #6

        Thank you very much for this enlightening information. :thumbsup:

        modified on Thursday, July 22, 2010 4:01 AM

        1 Reply Last reply
        0
        • L lgmanuel

          hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

          A Offline
          A Offline
          Aescleal
          wrote on last edited by
          #7

          If you're using C the various tricks other people have shown you will work, well, the XOR trick will, the add'em subtract'em one won't in all cases (you can't add two pointers although you can subtract them but can't use -=). Having said that I wouldn't bother too much unless it's an accademic exercise. Years ago when I worked in the games industry there were loads of tricks like this one which were meant to save clock cycles. However when, after loads of micro-optimisations like this one, someone actually did any timings there didn't turn out to be a lot of difference. Cheers, Ash

          P 1 Reply Last reply
          0
          • N Nuri Ismail
            1. With simple arithmetic operations:

            int x = 150;
            int y = 45;
            x = x + y;
            y = x - y;
            x = x - y;

            [EDIT] The above technique is dangerous because in some situations you can exceed the data types range!! Now I know (thanks to emilio_grv and his excellent post[^]) that this technique is not dangerous if the two variables are of the same integer type. [/EDIT] 2) The XOR swap:

            int x = 150;
            int y = 45;
            x ^= y;
            y ^= x;
            x ^= y;

            You can read more about the XOR swap here[^]. Also you can check out some CodeProject articles (and their message boards) on this topic: - A Curious Economic Swap[^] - The Stupid XOR Trick[^] :)

            modified on Thursday, July 22, 2010 3:56 AM

            A Offline
            A Offline
            Aescleal
            wrote on last edited by
            #8

            More importantly if you're into this sort of micro-optimisation then add'em subtract'em method only works on arithmetic types. Pointers need not apply. Cheers, Ash

            N E 2 Replies Last reply
            0
            • A Aescleal

              More importantly if you're into this sort of micro-optimisation then add'em subtract'em method only works on arithmetic types. Pointers need not apply. Cheers, Ash

              N Offline
              N Offline
              Nuri Ismail
              wrote on last edited by
              #9

              This is absolutely true! :thumbsup: I didn't mention that, because I thought it was obvious. But you are right - maybe it is not quite obvious for the OP, I should mention this fact. Thanks, :) Nuri

              1 Reply Last reply
              0
              • L lgmanuel

                hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                M Offline
                M Offline
                Maximilien
                wrote on last edited by
                #10

                lgmanuel wrote:

                am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'..

                why ? IMO, other than the fact that it uses a small "hack", there is no reason to use that in 2010. (or as a stupid interview question).

                Watched code never compiles.

                E S 2 Replies Last reply
                0
                • A Aescleal

                  More importantly if you're into this sort of micro-optimisation then add'em subtract'em method only works on arithmetic types. Pointers need not apply. Cheers, Ash

                  E Offline
                  E Offline
                  Emilio Garavaglia
                  wrote on last edited by
                  #11

                  Aescleal wrote:

                  Pointers need not apply

                  Not necessarily: swapping two pointers can be achieved by add/subtract if reinterpreted as integers of the appropriate size. Don't think to pointer as "addresses" and to integer as "numbers". Think in term of "sequence of bits". The triple xor (as well as the add subtract) is just a mechanism that mix-up the bits so that the ones that were on a place appear to the other and vice-versa. What the bit are used to represent what is indifferent. The important thing is that +- (as well of ^) are not the overloaded specific for the particular type, but just the integer ones. The only constrain is that the integer size (in bits) must be the same as the swapping type.

                  2 bugs found. > recompile ... 65534 bugs found. :doh:

                  A 1 Reply Last reply
                  0
                  • M Maximilien

                    lgmanuel wrote:

                    am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'..

                    why ? IMO, other than the fact that it uses a small "hack", there is no reason to use that in 2010. (or as a stupid interview question).

                    Watched code never compiles.

                    E Offline
                    E Offline
                    Emilio Garavaglia
                    wrote on last edited by
                    #12

                    consider this:

                    template<class A>
                    void xswap(A& a, A& b)
                    {
                    for(size_t i=0; i<sizeof(a); ++i)
                    {
                    ((char*)&a)[i] ^= ((char*)&b)[i];
                    ((char*)&b)[i] ^= ((char*)&a)[i];
                    ((char*)&a)[i] ^= ((char*)&b)[i];
                    }
                    }

                    This works even if A is a class one gigabyte wide, without allocate an extra gigabyte.

                    2 bugs found. > recompile ... 65534 bugs found. :doh:

                    N 1 Reply Last reply
                    0
                    • E Emilio Garavaglia

                      consider this:

                      template<class A>
                      void xswap(A& a, A& b)
                      {
                      for(size_t i=0; i<sizeof(a); ++i)
                      {
                      ((char*)&a)[i] ^= ((char*)&b)[i];
                      ((char*)&b)[i] ^= ((char*)&a)[i];
                      ((char*)&a)[i] ^= ((char*)&b)[i];
                      }
                      }

                      This works even if A is a class one gigabyte wide, without allocate an extra gigabyte.

                      2 bugs found. > recompile ... 65534 bugs found. :doh:

                      N Offline
                      N Offline
                      Niklas L
                      wrote on last edited by
                      #13

                      ...and who would ever handle such monster objects by value?

                      home

                      E W 2 Replies Last reply
                      0
                      • N Niklas L

                        ...and who would ever handle such monster objects by value?

                        home

                        E Offline
                        E Offline
                        Emilio Garavaglia
                        wrote on last edited by
                        #14

                        Depends on what the object represent: may be transfer buffers, one of which is shared with a DMA or another process. "Swap" merely means exchange the data visibility between devices, or processors. And since they are physically bounded to a device, cannot be swapped by reference (swapping the respective pointers). With less dimensions (typically, up to 4K or 9K), this exchanges are typically operated between the switch processors and the route processors of routers. Of course, is not something to be abused, but may have its own specific application.

                        2 bugs found. > recompile ... 65534 bugs found. :doh:

                        1 Reply Last reply
                        0
                        • E Emilio Garavaglia

                          Aescleal wrote:

                          Pointers need not apply

                          Not necessarily: swapping two pointers can be achieved by add/subtract if reinterpreted as integers of the appropriate size. Don't think to pointer as "addresses" and to integer as "numbers". Think in term of "sequence of bits". The triple xor (as well as the add subtract) is just a mechanism that mix-up the bits so that the ones that were on a place appear to the other and vice-versa. What the bit are used to represent what is indifferent. The important thing is that +- (as well of ^) are not the overloaded specific for the particular type, but just the integer ones. The only constrain is that the integer size (in bits) must be the same as the swapping type.

                          2 bugs found. > recompile ... 65534 bugs found. :doh:

                          A Offline
                          A Offline
                          Aescleal
                          wrote on last edited by
                          #15

                          I don't think of pointers as addresses - they're variables that store addresses. The problem with add'em substract'em with pointers is either your code ends up with either loads of casts OR spurious zeros:

                          x += (y - 0);

                          Which may or may not be bad depending on your point of view. Personally I'd just use std::swap and say sod the efficiency unless someone can show me in a profiler that it's too slow. Cheers, ash

                          1 Reply Last reply
                          0
                          • A Aescleal

                            If you're using C the various tricks other people have shown you will work, well, the XOR trick will, the add'em subtract'em one won't in all cases (you can't add two pointers although you can subtract them but can't use -=). Having said that I wouldn't bother too much unless it's an accademic exercise. Years ago when I worked in the games industry there were loads of tricks like this one which were meant to save clock cycles. However when, after loads of micro-optimisations like this one, someone actually did any timings there didn't turn out to be a lot of difference. Cheers, Ash

                            P Offline
                            P Offline
                            Peter Mulholland
                            wrote on last edited by
                            #16

                            I've been asked this one in an interview. I wasn't aware of the XOR swap at the time and I think I used a temp variable in my answer. I don't think I got an offer from that interview.

                            Pete

                            A 1 Reply Last reply
                            0
                            • M Maximilien

                              lgmanuel wrote:

                              am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'..

                              why ? IMO, other than the fact that it uses a small "hack", there is no reason to use that in 2010. (or as a stupid interview question).

                              Watched code never compiles.

                              S Offline
                              S Offline
                              stevev6
                              wrote on last edited by
                              #17

                              i think its a homework question.

                              1 Reply Last reply
                              0
                              • L lgmanuel

                                hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                                C Offline
                                C Offline
                                Craig Norton
                                wrote on last edited by
                                #18

                                Using Ruby: x, y = y, x

                                Try not to take life to seriously. When all is done no one gets out alive anyway.

                                1 Reply Last reply
                                0
                                • P Peter Mulholland

                                  I've been asked this one in an interview. I wasn't aware of the XOR swap at the time and I think I used a temp variable in my answer. I don't think I got an offer from that interview.

                                  Pete

                                  A Offline
                                  A Offline
                                  Aescleal
                                  wrote on last edited by
                                  #19

                                  I have been a couple of times as well - I'm a bit wary of taking any job that needs that sort of low level bit fiddling though. A good one to fire back at the interviewer is "I'll show you the C, you show me the boolean algebra proof." It's a good test of what the interviewer is like. Cheers, Ash

                                  1 Reply Last reply
                                  0
                                  • L lgmanuel

                                    hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                                    G Offline
                                    G Offline
                                    ghle
                                    wrote on last edited by
                                    #20

                                    Use the processor registers. No temp variable involved. Use assembly language of your choice. Fast! 4 CPU instructions w/4 memory waits & you're done!

                                    int x = 150;
                                    int y = 45;
                                    asm{
                                    LDA x;
                                    LDB y;
                                    STA y;
                                    STB x;
                                    }

                                    Using XOR, do it 3 times slower... 11 CPU instructions w/7 memory waits int x = 150; int y = 45; x ^= y; y ^= x; x ^= y;

                                    #DEFINE B 1
                                    int x = 150;
                                    int y = 45;
                                    asm{
                                    /* x ^= y */
                                    LDA x; /* A register = x */
                                    XOR y; /* A = A XOR y */
                                    STA x; /* x = A, i.e., x ^= y */

                                    /* y ^= x */
                                    STA B; /* B register = x */
                                    LDA y; /* A register = y */
                                    XOR B; /* A = A XOR B */
                                    STA y; /* y = A, i.e., y ^= x */

                                    /* x ^= y */
                                    STA B; /* B register = y */
                                    LDA x; /* A register = x */
                                    XOR B; /* A = A XOR B */
                                    STA x; /* x = A, i.e., x ^= y */
                                    }

                                    Otherwise, this other SLOW method... 12 CPU instructions w/6 memory waits x += y; y = x - y; x -= y;

                                    #DEFINE B 1
                                    int x = 150;
                                    int y = 45;
                                    asm{
                                    /* x = x + y; */
                                    LDA x; /* A register = x */
                                    LDB y; /* B register = y */
                                    ADA B; /* A register = A + B, i.e. A = x + y */
                                    STA x; /* Save A register to x */

                                    /* y = x - y */
                                    /* A contains x, B contains y */
                                    CMB; /* 1's complement B register, i.e. B = -y -1 */
                                    INB; /* increment (2's complement) B , i.e. B = -y */
                                    ADA B; /* Add B (-y) to A (x), i.e. A = x - y */
                                    STA y; /* Save A register to y */

                                    /* x = x - y */
                                    /* At this point, A contains y */
                                    CMA; /* 1's complement A register, i.e. A = -y -1 */
                                    INA; /* increment A (2's complement), i.e. A = -y */
                                    ADA x; /* Add x to A, i.e., A = -y + x */
                                    STA x; /* Save A register to x */
                                    }

                                    Notes for the unknowing: Operations on registers are much faster than memory access Negating a number is two's complement Two's complement is one's complement +1 One's complement reverses (NOTs) all bits Who loves Assembler??? :thumbsup: No JITCHIT X| either.

                                    Gary

                                    1 Reply Last reply
                                    0
                                    • L lgmanuel

                                      hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                                      B Offline
                                      B Offline
                                      BC3Tech
                                      wrote on last edited by
                                      #21

                                      Is this in the "Homework help" section? the only time i've ever needed to do this was CompSci 221. haha.

                                      1 Reply Last reply
                                      0
                                      • L lgmanuel

                                        hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                                        E Offline
                                        E Offline
                                        EbenRoux
                                        wrote on last edited by
                                        #22

                                        These kinds of interview questions are rather silly. Now really: what does it prove or show? Maybe that you know how to perform the swap using some weird trick, but as far as your abilities i.t.o. software design it shows nought. It will not work on strings, anyway.

                                        1 Reply Last reply
                                        0
                                        • L lgmanuel

                                          hi guys need help about my problem, am trying to swap the values of 'x' and 'y' without using a temporary storage like 'z'.. here is the code int x = 150 (or any integer value); int y = 45 (or any integer value); output: x = 45 y = 150 help guys, thanks ahead.

                                          C Offline
                                          C Offline
                                          codemunkeh
                                          wrote on last edited by
                                          #23

                                          int x = 450;
                                          int y = 45;
                                          Console.WriteLine("X = " + y);
                                          Console.WriteLine("Y = " + x);

                                          If you ask me, this fulfils the spec. Edit: oh and this works with strings, numbers, pointers (well maybe not if it's C#), or any datatype at all really.


                                          Ninja (the Nerd)
                                          Confused? You will be...

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups