Using an example will help.
For instance let a = 6 and b = 13.

a = a + b
Now a = 19 and b is unchanged at 13.

b - a - b or b = 19 - 13
Now a = 19 (unchanged) and b = 6.

a = a - b or a = 19 - 6
Now a = 13 and b = 6. The values are swapped.

For pure functionality, I don't recommend this method because it only works with summable values. Swapping using a temporary variable works in all cases.

>I don't recommend this method because it only works with summable values.
Not to mention that you also risk integer overflow and undefined behavior.

I don't think so. the result will be the fllowigs:
a=b;
b=0;

actually it does work

assume a = 3 and b = 7

a = a + b

a = 10
b = 7

b = a - b
a = 10
b = 3

a = a - b
a = 7
b = 3

however from the responses this doesnt seem to be a very safe way of handling things.

The most efficient way for swapping whole numbers is

int a = 10;
int b = 15;

a ^= b;
b ^= a;
a ^= b;

y because xor is an assembly level instruction and its much faster than any move operation.

>The most efficient way for swapping whole numbers is <snip xor swap>
>because xor is an assembly level instruction and its much faster than any move operation.
An empirical test disproves your claim. The swap using a temporary is noticeably faster on at least one compiler (Microsoft C++) given any optimization level.

``````#include <climits>
#include <ctime>
#include <iostream>

void swap_temp ( int& a, int& b )
{
int temp = a;
a = b;
b = temp;
}

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

int main()
{
int a1 = 10, a2 = 20;
int b1 = 10, b2 = 20;
std::clock_t start;

std::cout<< a1 <<"\t"<< a2 <<'\n';
std::cout<< b1 <<"\t"<< b2 <<'\n';

swap_temp ( a1, a2 );
swap_temp ( b1, b2 );

std::cout<< a1 <<"\t"<< a2 <<'\n';
std::cout<< b1 <<"\t"<< b2 <<'\n';

std::cout<<"swap_temp: ";
start = std::clock();
for ( unsigned i = 0; i < UINT_MAX; i++ )
swap_temp ( a1, a2 );
std::cout<< static_cast<double> ( std::clock() ) - start / CLOCKS_PER_SEC <<'\n';

std::cout<<"swap_xor: ";
start = std::clock();
for ( unsigned i = 0; i < UINT_MAX; i++ )
swap_temp ( b1, b2 );
std::cout<< static_cast<double> ( std::clock() ) - start / CLOCKS_PER_SEC <<'\n';
}``````

This sticky topic is a very interesting read but I think most of the articles are dwelling very low level C++ stuff which is not all wrong but in the current modern age and days and unless you are into compiler or device driver or OS kernel level programming, such esoteric constructs do not really apply to business application level programming.

Why was STL declared as part of the C++ standard? Simply becuz enough wasted years are spent on re-inventing code like vector, list, map, common algorithms starting from scratch. By mandating STL as part of C++ standard, it make us C++ programmer very fast up and running and devote more time to focus on our own company business domain logic!!!!

With ACE, I am now looking to deploy a portable multi-threaded server program in weeks instead of months or even years previously. I hope soon ACE will be part of C++ standard too. Java success is becuz Java Collections, Multi-thread, Logging, Socket, Generics, ImageIO,NIO etc etc are PART OF THE SDK. It make Java programmers more efficient in producing application level code as compared to traditional C++.

Back to performance tip. My working experience with a mission critical system using BEA Tuxedo is software design and IO are the two main culprits of low performance. A properly designed and efficient choice of data structures and algorithms of the module will yield magnitudes more performance than tweaking the C++ loop constructs, bitwise operations etc etc etc.

IO is the other killer. If possible structure your program such that just the correct number of times we need to do IO is enough. Additional IO accesses should be forbidden (if possible!!!). Despite commercial database boast of their performance, my working experience is doing the correct data structures and algorithms in programs will already give me the much higher performance I need. The database performance will be the icing on the cake though.

Lastly, I hope Java Hibernate and Swing concept can be part of C++ standard too. It is time C++ standard catch up with Java in the database access area and GUI. C++ still suffer from the syndrome of being too low level and not abstracted high enough for fast application level programming and uses.

>C++ still suffer from the syndrome of being too low level and not
>abstracted high enough for fast application level programming and uses.
You're missing the point, I think. C++ and Java aren't competing for the same market. Think of it this way: Java is good for high level applications. C++ is good for the frameworks (OS, JVM, compilers, etc...) that Java needs to exist. Don't forget that even though it can be used for applications, C++ is and always has been a systems programming language.

Great Job Guys !! Thanks.

Wow! I learned a lot of things from this thread! ... Thanks for the info everyone!!

Hello,
Thanks to share the tips of c++,you have taken these tips from the book Efficient c++,I think, Thinking in c++ is also a good book for c++,To Swap two variables, you use simple logic:
a=a+b;
b=a-b;
a=a-b;

commented: Done to death already, and it's rubbish - read the posts! -3

> 1. In VS 6.0 (on Intel H/W) (are unsigned better?)
So, you pick one specific processor / compiler combination out of the many 10's of processors (or maybe hundreds of variants, or thousands of compilers + flag variations) and decide that proves it?
Interesting it may be, but it's not in my "useful" things to know when it comes to getting the best out of the code.

The whole point of using a HLL is to stop you from having to worry about the minutia of how specific machines handle specific cases, and thus allow you to concentrate on the bigger issues.

Any (let me say it again for the hard of reading, ANY) attempt at performance optimisation before you've finished the program and done some meaningful profiling is a waste of time. Focus your effort on choosing good data structures and algorithms, which will save hours (or months) of computing time, and let the compiler worry about the microseconds.

Your fast loop won't mean squat if you were dumb enough to put it in a bubble sort for example. There isn't an optimiser out there which can spot a bubble sort and decide to replace it with quicksort. That's YOUR job, so do it.

If you're finding your "optimised" code hard to read, then for sure so will the compilers' optimiser, and it will just chicken out and do exactly what you asked for.

Take those ridiculous attempts at swapping variables (without a temp) for example.

What could possibly be wrong with

``````{ int temp = a ; a = b ; b = temp; }
printf( "%d %d\n", a, b );``````

Simple, obvious, and more importantly, TRANSPARENT to the optimiser. My recent version of gcc for example optimised this out to (wait for it) `printf( "%d %d\n", b, a );` That's right, the swap is GONE!

An extreme case maybe, but it does illustrate that if the code is clear in it's purpose, then the optimiser may just get rid of it and find another way to get to where you want to be.

With all those swap tricks, the optimiser is left with "Huh?, WTF is that" and you get exactly what you asked for.

Compilers have evolved a lot since the 1980's, so stop recycling all those 1980's tricks. They either don't work, are unnecessary or just make it worse.

commented: ! +7
commented: Omg... your post (#41) on page 5 was just too damn funny... +1

I have picked some ideas here about c++. Thanks gurus.

An easy way to swap 2 variables without using another variable:

``````a=a+b;
b=a-b;
a=a-b;``````

here's a one-statement version:

``a = a + b - (b = a);``
commented: Undefined Behaviour! -1

> here's a one-statement version:
Which is just as broken as all the other 1-statement attempts, which result in a variable (in this case b) being assigned before (or maybe after, who knows) the rest of the expression.

>The most efficient way for swapping whole numbers is <snip xor swap>
>because xor is an assembly level instruction and its much faster than any move operation.
An empirical test disproves your claim. The swap using a temporary is noticeably faster on at least one compiler (Microsoft C++) given any optimization level.

``````#include <climits>
#include <ctime>
#include <iostream>

void swap_temp ( int& a, int& b )
{
int temp = a;
a = b;
b = temp;
}

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

int main()
{
int a1 = 10, a2 = 20;
int b1 = 10, b2 = 20;
std::clock_t start;

std::cout<< a1 <<"\t"<< a2 <<'\n';
std::cout<< b1 <<"\t"<< b2 <<'\n';

swap_temp ( a1, a2 );
swap_temp ( b1, b2 );

std::cout<< a1 <<"\t"<< a2 <<'\n';
std::cout<< b1 <<"\t"<< b2 <<'\n';

std::cout<<"swap_temp: ";
start = std::clock();
for ( unsigned i = 0; i < UINT_MAX; i++ )
swap_temp ( a1, a2 );
std::cout<< static_cast<double> ( std::clock() ) - start / CLOCKS_PER_SEC <<'\n';

std::cout<<"swap_xor: ";
start = std::clock();
for ( unsigned i = 0; i < UINT_MAX; i++ )
swap_temp ( b1, b2 );
std::cout<< static_cast<double> ( std::clock() ) - start / CLOCKS_PER_SEC <<'\n';
}``````

I think I just noticed a mistake :icon_wink: You're comparing swap_temp for both tests, not quite sure why one takes longer than the other though?

>I think I just noticed a mistake
Transcription error. The stated result comes from correct code though.