Question

In most languages, if you want to swap two variables, it's something like:

var c = b
b = a
a = c

Yes, you can do fancy hacks with XOR if you like but it's generally 3 lines of code for a single operation. Are there any languages that have swapping variables as a primitive in the language?

Was it helpful?

Solution

Lua, Python, Ruby and more support this notation:

a, b = b, a

And javascript sure needs no temporary variable either ;)

a = -(b = (a += b) - b) + a;

For more examples on how to swap variables (in 86 languages), see: http://rosettacode.org/wiki/Generic_swap

OTHER TIPS

In most dynamic languages you can do something like this to swap:

a, b = b, a

Now a have the value of b, and b has the value of a. I am not sure if this is what you meant or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top