# Swap 2 objects, without using a temporary variable [closed]

There are two objects:

Object1, Object2


You can easily swap them by:

Object3 = Object1
Object1 = Object2
Object2 = Object3


However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

• Here we have a prime example of what is wrong with challenges that don't have "an objective winning criteria" as currently required by the FAQ: three different answer that are all completely correct. So how will people judge them? All that we have here is a popularity context. Nov 11 '12 at 20:31
• @dmckee, the problem here isn't lack of objective winning criteria, but of any winning criteria. Nov 11 '12 at 21:18
• Would this count in Python? a,b=b,a Nov 26 '18 at 20:55

## Python

I'll say it first.

object1, object2 = object2, object1

• Also possible in Go. However, I think a temporary variable may still be made in the compiled code. Nov 12 '12 at 15:22
• This is also valid Ruby. Nov 15 '12 at 20:16

## Mathematica

A standard feature:

a = 1; b = 2;
Print[a, " ", b];
{a, b} = {b, a};
Print[a, " ", b];


Output

(*
1 2

2 1
*)


PostScript

In PostScript, it's common to use the stack instead of named variables, so a simple

exch


would do the job. But if you have variables, you can do it like

/a 1 def
/b 2 def
/a b /b a def def


// return 0 for success, 1 for error
int swap(void *object1, void *object2, int size)
{
for (int i = 0; i < size; i++)
{
char *x = (char *)(object1 + i);
char *y = (char *)(object2 + i);
if (x == y)
return 1;
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
return 0;
}


per dmckee suggestion for clarity

• The solution is to pass a size as well, cast to char* and then xor swap the characters guarding against the same-value failure mode. Not as pretty, but standards compliant and working. Nov 11 '12 at 21:44
• Only answer which doesn't do a,b = b,a. +1 :) Nov 12 '12 at 22:16

## Perl

($object1,$object2) = ($object2,$object1);


Using Perl's list assertions feels like cheating, but it's a pretty common feature.

# PHP

Objects / arrays / resources:

list($a,$b) = [$b,$a];


Integers / booleans / strings of equal length:

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


## Forth

swap


As i have to include more than 30 characters, here's a link to a Forth primer