Solved

swapping two variables without a temp variable

Posted on 2001-06-08
4
236 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
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 member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

729 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