iam a 1st yr b.e stucent.i was attending my c.p lab viva.i was asked to write a program that would exchange 2 variables without using a third variable.i could'nt do it.i know how to exchange the values by using a third variable.someone please answer this question.

## All 2 Replies

It's fairly simple to write:

``````int a=5;
int b=3;

a = a ^ b;    // a will contain a xor b = 6
b = a ^ b;    // b will receive 6 xor 3 = 5
a = a ^ b;    // a will become 6 xor 5 = 3

printf("a=%d b=%d", a,b);``````

But personally I don't like it. I don't like the assignment and I don't like teachers who come up with this stuff.

The reason is that this can easily cause undefined behavior. Look at this line: `b = a ^ b;` What value does the right b have? You would say it has it's old value, but perhaps 'a' was already assigned to 'b' before the xor operation was carried out. What would happen then??

You should tell your teacher that this is a worthless assignment and that this horror of a code will only teach bad coding habits and major problems if ever used in a real project.

commented: I did not know this method existed :) +2

Another alternative.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.