문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top