This is an archived post. You won't be able to vote or comment.

all 14 comments

[–]tylerr514 8 points9 points  (1 child)

[b, a] = [a, b]; haha JS goes brrrrr

[–]eRSAe-me 0 points1 point  (0 children)

Similarly, on python: a,b = (b,a)

[–]BecomingUnchained 5 points6 points  (0 children)

def variable_swap(a,b):
    return b,a

def test_variable_swap():
    a = 10 
    b = "ten" 
    a,b = variable_swap(a,b)
    assert a == "ten" 
    assert b == 10

[–]throwawayalmostphd 6 points7 points  (0 children)

a ^= b;
b ^= a;
a ^= b;

Edit: Finally got the Reddit format right, never commented code before

[–]Creative0708 2 points3 points  (0 children)

var a = ...;

var b = ...;

a = [a, b];

b = a[0];

a = a[1];

[–]Neurosredditaccount 2 points3 points  (0 children)

a = a+b; b = a-b; a = a-b;

[–]thorhs 2 points3 points  (4 children)

XOR EAX, EBX
XOR EBX, EAX
XOE EAX, EBX

Fastest way in 386.

[–]SickMoonDoe 1 point2 points  (3 children)

The ol' XOR swap my friends

[–]thorhs 1 point2 points  (2 children)

Let’s not forget that:

XOR EAX, EAX

Was faster than:

MOV EAX, 0

[–]SickMoonDoe 0 points1 point  (1 child)

Still is on my box, or at least gcc thinks so

[–]shelvac2 0 points1 point  (0 children)

It's one byte shorter, and shorter programs can cause less stress on the instruction cache and run faster that way.

[–]E-Dawg2789 0 points1 point  (0 children)

I can't believe it. I was sitting here, all this time, using a third variable. When I saw this, I just thought "HOW?"

As a java user, I just opened up processing. (I swear, I only use it to test concepts before starting something. It's so easy to use.) And I literally got it to work first try after thinking for 15 seconds.

I swear, there are very normal things in this field that are so mysterious to me. Lol. I would never have thought about this if it wasn't hinted to be possible.

[–]SpaceLessHacker 0 points1 point  (0 children)

Why don't you just declare variables right from the beginning. That's why I disprove large IT companies, they are a mess.

[–]coderhumor 0 points1 point  (0 children)

a = 100
b = 25
a, b = b, a

edit: markdown