RAYYILDIZ wrote:
> I Know C is the fastest progrmming language. However, by using some
> bitwise operation you can get faster the your program.
> For instance, we talk about swap function. For a integer swapping we
> use this generally.
>
> void swap(int* a,int* b){
> int c;
> c=*a;
> *b=*a;
> *b=c;
> }
>
> we use a local variable and swapping varibales with each other, it may
> be expensive. We do this swap function like that:
>
> void swap(int*a ,int *b){
> *a ^= *b;
> *b ^= *a;
> *a ^= *b;
> }
>
NNNNNNNNOOOOOOOOOO!!!!!!!!!!!
The XORing version, on C++ compiler I've ever used is SLOWER once you
enable even basic optimisation.
SSSSLLLOOOWWWEEERR!!
(sorry, but this comes up so often). Any modern compiler can easily
remove unused variables, or just keep them in a register. They aren't
stupid!
Lets see what the average compiler will do (I check g++ 3.3 at
optimisation -O1):
For your first swap function, any compiler on any optimisation level
will produce the code (sudo-assembler)
read *a into register 1
read *b into register 2
write register 1 into *b
write register 2 into *a
Your code will produce:
read *a into register 1
read *b into register 2
register 1 = register 1 XOR register 2
register 2 = register 2 XOR register 1
register 1 = register 1 XOR register 2
put register 1 into *a
put register 2 into *b
As you can see, your code is clearly taking longer
Chris