Search code examples
variablesprogramming-languageslanguage-features

Which languages have a primitive operation for swapping variables?


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?


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