473,387 Members | 1,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

swap two numbers

hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.
Nov 14 '05 #1
21 16824
Abhishek Jha wrote:
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


a = a-(b=(a=a+b)-b);

--
USENET would be a better place if everybody read:
http://www.expita.com/nomime.html
http://www.netmeister.org/news/learn2quote2.html
http://www.catb.org/~esr/faqs/smart-questions.html
Nov 14 '05 #2

"Abhishek Jha" <ab***********@yahoo.co.in> wrote in message
news:60**************************@posting.google.c om...
hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


[ a=a+b;b=a-b;a=a-b; ] is a bad way to swap two numbers due to possible
overflow. A better method without using a temporary variable is to use the
XOR trick[*] (which works for non-integral types as well). But, the best
way is probably just to use a standard temporary variable and let the
compiler do the optimization.
[*] a^=b; b^=a; a^=b;
Nov 14 '05 #3

Pedro Graca wrote:
Abhishek Jha wrote:
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also done in three statements. Can anyon suggest this swapping in anything less then that.


a = a-(b=(a=a+b)-b);


This is even worse than the original silliness as it always invokes
undefined behavior.

Rob Gamble

Nov 14 '05 #4
ab***********@yahoo.co.in (Abhishek Jha) writes:
hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


C FAQ <http://www.eskimo.com/~scs/C-faq/q10.3.html>, question 10.3.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #5
On Sat, 16 Oct 2004 16:45:22 +0000, Pedro Graca wrote:
Abhishek Jha wrote:
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


a = a-(b=(a=a+b)-b);


int a = INT_MAX;
int b = a;

... (a = a+b) whoops.
Nov 14 '05 #6
Abhishek Jha wrote:
hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.

What if a+b overflows ?
And is there any point to do "smart" tricks like this ? If one
needs to swap variables, do it the right way. If there is
anything to gain, trust your compiler to optimize it.
Nov 14 '05 #7
> [ a=a+b;b=a-b;a=a-b; ] is a bad way to swap two numbers due to possible
overflow. A better method without using a temporary variable is to use the
XOR trick[*] (which works for non-integral types as well). But, the best

^^^^^^^^^^^^^^^^^^^^

What do you mean by this? The trick won't work for floats, doubles or
pointers
for instance.
Nov 14 '05 #8

"Nils O. Selåsdal"
What if a+b overflows ?
And is there any point to do "smart" tricks like this ? If one
needs to swap variables, do it the right way. If there is
anything to gain, trust your compiler to optimize it.

You're basically right, but not about trusting the compiler. Let's say that
the XOR hack saves a cycle over use of a temporary, due to the architecture
of the instruction set. Seeing that assignment to a temporary is only for
the purposes of swapping is the sort of thing compilers tend not to be good
at, because they don't see the source with a human eye. However is saving a
cycle really worth it? If you are so time critical, wouldn't it be better to
resort to assembly?
Nov 14 '05 #9
In article <ck**********@newsg4.svr.pol.co.uk> "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
"Nils O. Selåsdal"
What if a+b overflows ?
And is there any point to do "smart" tricks like this ? If one
needs to swap variables, do it the right way. If there is
anything to gain, trust your compiler to optimize it.

You're basically right, but not about trusting the compiler. Let's say that
the XOR hack saves a cycle over use of a temporary, due to the architecture
of the instruction set. Seeing that assignment to a temporary is only for
the purposes of swapping is the sort of thing compilers tend not to be good
at,


Compilers tend to be very good at just that. Using the tmp variable
will much more likely get the optimal sequence:
load a to r1
load b to r2
store r2 to a
store r1 to b
on most machines. Using the xor trick (or whatever) may very well lead
to:
load a to r1
load b to r2
set r1 to r1 ^ r2
set r2 to r2 ^ r1
set r1 to r1 ^ r2
store r1 to a
store r2 to b
on the same machines.

The point is, tell the compiler what you want, do not obfuscate it.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #10
"Abhishek Jha" <ab***********@yahoo.co.in> wrote in message
news:60**************************@posting.google.c om...
hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


Trite academic exercises aside, who needs a 'clever' way to swap two
numbers?
Nov 14 '05 #11
>"Nils O. Selåsdal"
What if a+b overflows ?
And is there any point to do "smart" tricks like this ? If one
needs to swap variables, do it the right way. If there is
anything to gain, trust your compiler to optimize it.

In article <news:ck**********@newsg4.svr.pol.co.uk>
Malcolm <ma*****@55bank.freeserve.co.uk> wrote:You're basically right, but not about trusting the compiler. Let's say that
the XOR hack saves a cycle over use of a temporary, due to the architecture
of the instruction set. Seeing that assignment to a temporary is only for
the purposes of swapping is the sort of thing compilers tend not to be good
at, because they don't see the source with a human eye.
No; they see it with one that makes no mistakes, instead. :-)

This is actually a very simple optimization in any compiler that
does live-range analysis of variables. The "live range" of a
variable begins from when it is first assigned and ends at the
last reference to it before it is assigned another value (or the
last reference, if never re-assigned). This means that, for
instance, in code like:

tmp = a; /* line 17 */
a = b;
b = tmp; /* line 19 */
tmp = c; /* line 20 */
c = d;
d = tmp; /* line 22 */
/* code that does not refer to "tmp" again */

the "tmp" variable has two separate live ranges: one covers lines
17 through 19, and the other lines 20 through 22.

Given this information, and assuming that a, b, c, and d are in
processor registers and the CPU has a "swap" instruction for swapping
a pair of registers, it is easy to generate code of the form:

swap rA, rB
swap rC, rD

for these six lines of code. The GNU C compiler does it, for
instance. (Of course, the person who writes the ".md" file for
the machine has to define the swap instruction.)
However is saving a cycle really worth it? If you are so time
critical, wouldn't it be better to resort to assembly?


This is a valid point -- but it turns out that many C programmers
can no longer write "fast assembly code" for modern (pipelined)
processors -- or at least, not as well as compilers with good
pipeline schedulers (gcc3's is far better than gcc2's, for instance).
To beat the compiler, you may need one of those special assembly
programmers stored in the glass cases (with the signs that read
"in case of emergency, break glass"). :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #12
On Sat, 16 Oct 2004 23:42:11 +0100, Malcolm wrote:
What if a+b overflows ?
And is there any point to do "smart" tricks like this ? If one
needs to swap variables, do it the right way. If there is
anything to gain, trust your compiler to optimize it.
You're basically right, but not about trusting the compiler. Let's say that
the XOR hack saves a cycle over use of a temporary, due to the architecture
of the instruction set. Seeing that assignment to a temporary is only for

Then I would call it a non-optimal compiler. Take a look at
optimized compiler compiler generated assembly, there isn't always that
much resemblance with the corresponding C code ;) the purposes of swapping is the sort of thing compilers tend not to be
good at, because they don't see the source with a human eye. However is
saving a cycle really worth it? If you are so time critical, wouldn't it
be better to resort to assembly?

Lets just not hope the C compiler does funny things then;
"The order of evaluation of subexpressions within an expression is
undefined."
Nov 14 '05 #13
On Sun, 17 Oct 2004 00:24:10 +0000, Dik T. Winter wrote:
In article <ck**********@newsg4.svr.pol.co.uk> "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
> "Nils O. Selåsdal"
> > What if a+b overflows ?
> > And is there any point to do "smart" tricks like this ? If one
> > needs to swap variables, do it the right way. If there is
> > anything to gain, trust your compiler to optimize it.
> >

> You're basically right, but not about trusting the compiler. Let's say that
> the XOR hack saves a cycle over use of a temporary, due to the architecture
> of the instruction set. Seeing that assignment to a temporary is only for
> the purposes of swapping is the sort of thing compilers tend not to be good
> at,


Compilers tend to be very good at just that. Using the tmp variable
will much more likely get the optimal sequence:
load a to r1
load b to r2
store r2 to a
store r1 to b

looking at compiler output using a
inline void swap(int *a,int *b);
For 4 real world examples I've tested now, the compiler
optimizes away the entire swap altogether, it just seems to
reorder things so the swap isn't even needed :)

Nov 14 '05 #14
In article <pa****************************@Utel.no> =?iso-8859-1?q?Nils_O=2E_Sel=E5sdal?= <NO*@Utel.no> writes:
On Sun, 17 Oct 2004 00:24:10 +0000, Dik T. Winter wrote:

....
Compilers tend to be very good at just that. Using the tmp variable
will much more likely get the optimal sequence:
load a to r1
load b to r2
store r2 to a
store r1 to b

looking at compiler output using a
inline void swap(int *a,int *b);
For 4 real world examples I've tested now, the compiler
optimizes away the entire swap altogether, it just seems to
reorder things so the swap isn't even needed :)


Oh, yes, for inlined functions that is pretty probable. I have worked
with tuning an Algol 68 compiler that with the probably tuning after
a switch still did know what was where, and optimized branches to
store the same thing in the same place. But that was only 1970s
technology.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #15
On Sat, 16 Oct 2004 12:53:25 -0400, "Method Man" <a@b.c> wrote in
comp.lang.c:

"Abhishek Jha" <ab***********@yahoo.co.in> wrote in message
news:60**************************@posting.google.c om...
hello all,
this has been an interesting topic since long. you can swap two
numbers (say a and b) using temp(as third variable). you can also swap
without using third variable.like[ a=a+b;b=a-b;a=a-b; ]This was also
done in three statements. Can anyon suggest this swapping in anything
less then that.


[ a=a+b;b=a-b;a=a-b; ] is a bad way to swap two numbers due to possible
overflow. A better method without using a temporary variable is to use the
XOR trick[*] (which works for non-integral types as well). But, the best
way is probably just to use a standard temporary variable and let the
compiler do the optimization.

[*] a^=b; b^=a; a^=b;


Except of course that it does not work for non-integer types at all,
and may generate a trap representation and thus undefined behavior on
signed integer types.

Works like a charm on all unsigned integer types, though.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #16

"Jarmo" <ja***@jarmo.com> wrote

Trite academic exercises aside, who needs a 'clever' way to swap two
numbers?

consider this

int gcf(int x, int y)
{
if(x < y)
swap(x, y);
if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

And this

int gcf(int x, int y)
{
int temp;

if(x < y)
{
temp = x;
x = y;
y = temp;
}

if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

Which one is clearer?
Nov 14 '05 #17
Malcolm wrote:

"Jarmo" <ja***@jarmo.com> wrote

Trite academic exercises aside, who needs a 'clever' way to swap two
numbers?

consider this

int gcf(int x, int y)
{
if(x < y)
swap(x, y);
if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

And this

int gcf(int x, int y)
{
int temp;

if(x < y)
{
temp = x;
x = y;
y = temp;
}

if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

Which one is clearer?


My first impulse after scanning the code, was to say the second one.
The second one, is entirely defined within your post.

I was scanning the code quickly.
When I saw the function call, without even reading it,
my mind said
"put that on that back burner and let's see
what the rest of this code is all about"

If I had been reading more slowly, I would have read the name
of the function and guessed what it meant.
Now that I am really taking my time,
I even realise that swap() is a macro and not a fuction.

If I were debugging the code,
I would have to look up the definition of swap().

swap() is easy to read, but this:

temp = x;
x = y;
y = temp;

is very easy to read.

--
pete
Nov 14 '05 #18
Jack Klein wrote:
"Method Man" <a@b.c> wrote:

.... snip ...

[*] a^=b; b^=a; a^=b;


Except of course that it does not work for non-integer types at all,
and may generate a trap representation and thus undefined behavior
on signed integer types.

Works like a charm on all unsigned integer types, though.


Except when told to swap an item with itself, when it has a
penchant for zeroing the whole mess in disgust.

--
"I support the Red Sox and any team that beats the Yankees"

"Any baby snookums can be a Yankee fan, it takes real moral
fiber to be a Red Sox fan"

Nov 14 '05 #19
"CBFalconer" <cb********@yahoo.com> wrote in message
news:41***************@yahoo.com...
--
"I support the Red Sox and any team that beats the Yankees"

"Any baby snookums can be a Yankee fan, it takes real moral
fiber to be a Red Sox fan"


Catch yesterday's game? Yikes!

-Mike
(Another NYY hater). Go Sox! :-)
Nov 14 '05 #20
hello malcolm,
You have written nice function to swap, but what is this swap().

"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<ck**********@newsg1.svr.pol.co.uk>...
"Jarmo" <ja***@jarmo.com> wrote

Trite academic exercises aside, who needs a 'clever' way to swap two
numbers?

consider this

int gcf(int x, int y)
{
if(x < y)
swap(x, y);
if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

And this

int gcf(int x, int y)
{
int temp;

if(x < y)
{
temp = x;
x = y;
y = temp;
}

if(x % y == 0)
return y;
else
return gcf(y, x % y);
}

Which one is clearer?

Nov 14 '05 #21
Abhishek Jha <ab***********@yahoo.co.in> scribbled the following:
hello malcolm,
You have written nice function to swap, but what is this swap().
And besides, how could it ever work when you pass the ints themselves
and not pointers to them?
Perhaps it's not a function at all, but instead a macro.
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<ck**********@newsg1.svr.pol.co.uk>...
int gcf(int x, int y)
{
if(x < y)
swap(x, y);
if(x % y == 0)
return y;
else
return gcf(y, x % y);
}


--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"A friend of mine is into Voodoo Acupuncture. You don't have to go into her
office. You'll just be walking down the street and... ohh, that's much better!"
- Stephen Wright
Nov 14 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: ma740988 | last post by:
So I'm reading the C++ coding standards(Shutter & Andrei), more specifically item 56. There's a statement: "Prefer to provide a nonmember swap function in the same namespace as your type when...
7
by: Kai-Uwe Bux | last post by:
Hi folks, I am still struggling with the rules for name lookup. Please consider: namespace xxx {
14
by: pras.vaidya | last post by:
hi, please help me with this problem : - how to swap two addresses .For eg variable i is located at 2000 and j at 3000 . Now i call swap function . Result should be that i should be now having...
9
by: Jongmin Lee | last post by:
Hi Everybody, I have very simple code snippet to explain my problem. Class "Swap" is construncted in "Main" with two initial variables. Later, "Swap" class is going to swap those two...
4
by: Niels Dekker (no reply address) | last post by:
When calling swap as follows (as recommanded in Effective C++, 3rd Edition, by Scott Meyers), what swap is chosen to be called? using std::swap; swap(a, b); Suppose there is a global ::swap...
3
by: idle | last post by:
#include<stdio.h> void swap(int &, int &); void main(){ int num1, num2; printf("Enter 2 numbers > "); scanf("%d%d", &num1, &num2);
9
by: ma740988 | last post by:
Consider: # include <vector> # include <iostream> # include <cstdlib> # include <ctime> bool ispow2i ( double n ) {
28
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't...
4
by: George2 | last post by:
Hello everyone, The following swap technique is used to make assignment operator exception safe (means even if there is exception, the current object instance's state is invariant). It used...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.