Solved

swapping two variables without a temp variable

Posted on 2001-06-08
4
202 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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 goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
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.

707 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

16 Experts available now in Live!

Get 1:1 Help Now