PostHeaderIcon Swapping Two Numbers Without a Temporary

It is easy, you can search with Google, but maybe you do not know more about it.

Let us look the code first(two ways):

one:

void jerry_swap( int& a, int& b )
{
	b=a+b;
	a=b-a;
	b=b-a;
}

two:

void jerry_swap( int& a, int& b )
{
	a^=b;
	b^=a;
	a^=b;
}

Some or many coders thought them as cool code.
But do you know today the compliers can optimize them on best way.
If we change our test to force the actual swapping of the variables we get the following code:

mov reg1, a
mov reg2, b
mov a, reg2
mov b, reg1

This demo lets us illustrate several attributes of a true hacker.
The first is a willingness to think outside the box.
Anyone can look up the standard answer on the Internet.
But only a good hacker will ask the question “Hey, what will happen if ….”
and then perform a bunch of experiments answering that question.
If the hacker is really good you find yourself with an answer
that is surprising and much better than the “standard” answer.

14,527 views

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Copyright © 2010 - C++ Technology. All Rights Reserved.

Powered by Jerry | Free Space Provided by connove.com