# Thread: Swapping 2 variables in C

1. ## Swapping 2 variables in C

Hi! I'm quite new to C programming, and I'd be glad if you could help me solve this little problem I'm having at the moment please..

I need to input 2 integer numbers (e.g. int a; int b, read them (e.g. a=10; b=17; or any value that may be input by the user), then swap them without using a 3rd temporary variable

Thanks and regards

2. #define sawp(a, b) (a ^= b ^= a ^= b)

4. Code:
```void swap( int &x, int &y ) {
int temp;
temp = x;
x = y;
y = temp;
}

or

void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}```

5. Originally posted by dharh
Code:
```void swap( int &x, int &y ) {
int temp;

}

or

void swap(int *x, int *y) {
int temp;
}```
You obviously missed the original question. They said without a temporary variable. Doubtless this is one of those homework problems that are supposed to increase your knowledge, but in fact just end up teaching you how to do things the Wrong Way(TM).

Quzah.

6. Every now and then I throw code around, sorry if a decapitate a head or two.

7. Code:
```int a;
int b;

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

8. Hmmm...I am not sure why you don't want to use a temporary variable.

Code:
```int a, b, temp

//first we'll swap with no temp
a = 4;
b = -35;

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

//now with the temp
a = 4;
b = -35;

temp = a;
a = b;
b = temp;```
The reason I question why you choose to do things without the temp is because its operational overhead exceeds whatever memory conservation it provides. I assume this is some sort of assignment that is to only reasonable explanation for this attempt.

9. Originally posted by dharh
Every now and then I throw code around, sorry if a decapitate a head or two.
I throw out code from time to time also. However, I was just letting you know that they were asking how to do it without another variable.

Quzah.

10. This is the understanding that there are lots of ways to solve a problem. And he presented an interesting way.. every one cannot do it in a second.

11. Originally posted by zahid
This is the understanding that there are lots of ways to solve a problem. And he presented an interesting way.. every one cannot do it in a second.
Actually, with the specifications the original poster provided, there are very few ways to solve this. The two most common are addition and XOR-ing.

Quzah.