Solved

swapping two variables without a temp variable

Posted on 2001-06-08
4
211 Views
Last Modified: 2010-04-02
suggest code in C to swap two variables without using a temporary variable. preferably a single statement.
0
Comment
Question by:falkon
  • 2
4 Comments
 
LVL 5

Accepted Solution

by:
proskig earned 50 total points
ID: 6166959
 b ^= a;
  a ^= b;
  b ^= a;

b and a will be swapped


Note also that it is C++ area
0
 
LVL 1

Expert Comment

by:harrlow
ID: 6173264
Using C..

a = a + b;
b = a - b;
a = a - b;
0
 
LVL 5

Expert Comment

by:proskig
ID: 6176416
The obvious problem with harrlow's code is that it does not work in general case due to size limit (just suppose that a and b are int's and they are close to INT_MAX)
0
 

Expert Comment

by:EliezerGarza
ID: 7590358
but you can use:
   a=a-b
   b=a+b
   a=b-a
instead of:
   a=a+b
   b=a-b
   a=a-b
or for extra CPU usage:
   a=a*b
   b=a/b
   a=a/b
or any other of many ways. This is just an academical question, so the important thing is not if it works 100% of the cases or not, but how would you do it.

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now