Wednesday 29 April 2009

Exchanging two variables value without using temporary storage in C language

You can exchange values in C language without the need of the temporary storage location using three bitwise Exclusive-OR operator, look at code below:



#include <stdio.h>

int main(int argc, char *argv[])
{
int A;
int B;

A = 16;
B = 30;

printf("A=%d B=%d\n",A,B);
A ^= B;
B ^= A;
A ^= B;
printf("A=%d B=%d\n",A,B);

return 0;
}





The code after compiled will exchange value of variabel A with B, where A = 16 and B = 30 become A = 30 and B = 16.

How it works?
Value of A is XOR-ed with B value, the result then stored in A, then B XOR-ed with the altered A , this will produce the original value of A, this value then stored in B. Last, altered A value is XOR-ed with the altered B, this will produce the original B.


Here the schematically detail of its process:

A = 16 (decimal) --> 10 (hexadecimal) --> 0001 0000 (binary)
B = 30 (decimal) --> 1E (hexadecimal) --> 0001 1110 (binary)

on A ^= B statement, A being XOR-ed with B:

0001 0000 --> A
0001 1110 --> B
---------- XOR
0000 1110 --> A

the result 0000 1110 then stored in A,

on B ^= A statement, B being XOR-ed with A:

0001 1110 --> B
0000 1110 --> A
---------- XOR
0001 0000 --> B

the result 0001 0000 (16 decimal) stored in B,

on A ^= B statement, B XOR-ed with A:

0000 1110 --> A
0001 0000 --> B
---------- XOR
0001 1110 --> A

the result 0001 1110 (30 decimal) stored in A.

So the final result is:
A = 30 dan B = 16.



Have a nice try :).

No comments: