Jump to content

swapping

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
7 replies to this topic

#1
Chinmoy

Chinmoy

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 392 posts
here is a really simple program to swap 2 numbers without using a third variable.

say you have 2 numbers a and b;
now what you do is add a in b.
then save b-a in a.now save b-a in b.


{
int a=3,b=2;
cout<<"Initially to "<<a<<" "<<b;
{
b+=a;
a=b-a;
b=b-a;
}
cout<<"Swapped to "<<a<<" "<<b;
}

take care of the sequence.b takes a+b. now we put b in a by a=(b-a);meaning a=b(initial value).so now a=b-initial.so b=b-a..
simple.

#2
Chinmoy

Chinmoy

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 392 posts
try to do this with pointers..

#3
broncoslb

broncoslb

    Learning Programmer

  • Members
  • PipPipPip
  • 34 posts
I like it....thinking outside the box

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
This is not so much of thinking outside the box as it is thinking like we're in the 70's. This is an unoptimization that exhibits undefined behavior.

#5
Walle

Walle

    Learning Programmer

  • Members
  • PipPipPip
  • 75 posts

dcs said:

This is not so much of thinking outside the box as it is thinking like we're in the 70's. This is an unoptimization that exhibits undefined behavior.

Is it?

What behavior is undefined?

What would you say is a smarter way to do it?
________________________________________________
"I'm not young enough to know everything." - Oscar Wilde

#6
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

Walle said:

Is it?

What behavior is undefined?
When signed arithmetic over/underflows, the behavior is undefined.

Walle said:

What would you say is a smarter way to do it?
The obvious way, using a temporary.

#7
Walle

Walle

    Learning Programmer

  • Members
  • PipPipPip
  • 75 posts
Ah, I get it.

How about unsigned behaviour on overflow? Always wrap or is it also undefined?
________________________________________________
"I'm not young enough to know everything." - Oscar Wilde

#8
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
Unsigned integer overflow is well-defined as wrapping.