943,755 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 1865
  • C RSS
Apr 18th, 2008
0

exchange 2 varibles withoutb using a third variable

Expand Post »
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.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
abcd_nima is offline Offline
5 posts
since Mar 2008
Apr 18th, 2008
1

Re: exchange 2 varibles withoutb using a third variable

It's fairly simple to write:

  1. int a=5;
  2. int b=3;
  3.  
  4. a = a ^ b; // a will contain a xor b = 6
  5. b = a ^ b; // b will receive 6 xor 3 = 5
  6. a = a ^ b; // a will become 6 xor 5 = 3
  7.  
  8. 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.
Last edited by Nick Evan; Apr 18th, 2008 at 7:21 am.
Moderator
Featured Poster
Reputation Points: 4142
Solved Threads: 394
Industrious Poster
Nick Evan is offline Offline
4,132 posts
since Oct 2006
Apr 18th, 2008
0

Re: exchange 2 varibles withoutb using a third variable

Another alternative.

a=a-b
b=b+a
a=b-a
Reputation Points: 46
Solved Threads: 24
Posting Whiz in Training
hammerhead is offline Offline
248 posts
since May 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: pipes: problem - simplified
Next Thread in C Forum Timeline: any pointers on how to do this





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC