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#

asked Jan 29, 2015 at 4:43
6
  • 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? Commented Jan 29, 2015 at 5: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. Commented Jan 29, 2015 at 5:03
  • 1
    @Asad So is arguably wanting to swap two variables without impacting the heap. This question represents questionable benefit Commented Jan 29, 2015 at 5:06
  • 2
    @MickyDuncan This is a rather typical interview question. Commented Jan 29, 2015 at 5:16
  • @EsotericScreenName Thanks. Yes for floating-point it is quite important. Commented Jan 29, 2015 at 5:19

5 Answers 5

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.

answered Jan 29, 2015 at 5:15
Sign up to request clarification or add additional context in comments.

Comments

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
answered Jan 29, 2015 at 4:49

Comments

3

There are actually a couple of ways.

The following is considered an obfuscated swap.

a ^= b;
b ^= a;
a ^= b;
answered Jan 29, 2015 at 4:46

Comments

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

Works the same with any language.

answered Jan 29, 2015 at 4:46

1 Comment

Just watch out for overflow :p
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/

answered Jan 29, 2015 at 4:48

Comments