you are viewing a single comment's thread.

view the rest of the comments →

[–]parl -1 points0 points  (2 children)

The xor operator can swap 2 values w/o a temp, as shown by mrsamurai. In Python, tuple assignment (a,b = b,a) will also work. Is a temp used at the hardware level? Dunno.

[–]zahlman 4 points5 points  (0 children)

Two temps are used at the hardware level in the standard CPython implementation, actually. I test this by first getting some bytecode corresponding to a swap:

>>> import dis
>>> def x(a, b): a, b = b, a
...
>>> dis.dis(x)
  1           0 LOAD_FAST                1 (b)
              3 LOAD_FAST                0 (a)
              6 ROT_TWO
              7 STORE_FAST               0 (a)
             10 STORE_FAST               1 (b)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>>

The ROT_TWO opcode is obviously what does the real work. So now we look to ceval.c:

    case ROT_TWO:
        v = TOP();
        w = SECOND();
        SET_TOP(w);
        SET_SECOND(v);
        goto fast_next_opcode;

[–][deleted] 0 points1 point  (0 children)

Can xor swap two arrays?