3

Swap two variables without using a temp variable if

int a=4; 
int b=3;

I need to swap these variable and get output as a=3 and b=4 without using another variable in C#

  • Any particular reason? I would have thought 3 MSIL **assignments** (`t = a; a=b; b=t; )` to be faster than **3 MSIL operations** followed by **3 assignments** judging by the answers below? –  Jan 29 '15 at 05:00
  • @MickyDuncan The speed is completely irrelevant here. There is no way anyone could have sat down to optimize their code and discovered the bottleneck was an extra statement when swapping two values. – Asad Saeeduddin Jan 29 '15 at 05:03
  • 1
    @Asad So is arguably wanting to swap two variables without impacting the heap. This question represents questionable benefit –  Jan 29 '15 at 05:06
  • 2
    @MickyDuncan This is a rather typical interview question. – Esoteric Screen Name Jan 29 '15 at 05:16
  • @EsotericScreenName Thanks. Yes for `floating-point` it is quite important. –  Jan 29 '15 at 05:19
  • **paxdiablo's** answer [here](http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable) makes a good point. _"developers who try to use tricks to, for example, swap variables without using a temp or 'Duff's device' are just trying to show how clever they are"_. –  Jan 29 '15 at 14:24

5 Answers5

7

Use Interlocked.Exchange()

int a = 4;
int b = 3;

b = Interlocked.Exchange(ref a, b);

Tell me more

From MSDN:

Sets a 32-bit signed integer to a specified value as an atomic operation, and then returns the original value

EDIT: Regarding Esoteric's fine link above (thank-you), there's even a Interlocked.Exchange() for double that may help there too.

5

use the following concept

int a=4 ;
int b=3 ;

a=a+b ;  //  a=7
b=a-b ;  //  b=7-3=4
a=a-b ;  //  c=7-4=3
AcAnanth
  • 765
  • 3
  • 19
  • 53
3

There are actually a couple of ways.

The following is considered an obfuscated swap.

a ^= b;
b ^= a;
a ^= b;
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
1
a = a + b;
b = a - b;
a = a - b;

Works the same with any language.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

Using addition and subtraction

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

Using xor operator

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

http://chris-taylor.github.io/blog/2013/02/25/xor-trick/

mmaynar1
  • 326
  • 4
  • 14