PDA

View Full Version : c++ doubt



netrix
May 9th, 2007, 04:37 PM
Hello guys, I need to learn a few basics about C++ for friday... can anyone tell me what does this C++ macro accomplish: #define func(a, b) a ^= b ^= a ^= b?! thanks in advance!

Templarian
May 9th, 2007, 05:58 PM
Without actually knowing C++,

^= is the XOR equals operator

BradLee
May 9th, 2007, 06:15 PM
At a glance, it looks very similar to the XOR swap algorithm, which swaps the values of a and b.

Jeff Wheeler
May 9th, 2007, 06:43 PM
Yeah, I agree. It looks like it would swap the values.

Templarian
May 9th, 2007, 08:07 PM
At a glance, it looks very similar to the XOR swap algorithm, which swaps the values of a and b.
creepy thats like exactly what my brother said when he looked over it real fast. Then he tried to explain how it didn't use a temporary variable so I just posed that.

hybrid101
May 10th, 2007, 08:49 AM
that is some nice code:lol:

Al6200
May 11th, 2007, 07:54 AM
Wow, it actually swaps:

a = 1010
b = 1101

a ^= b

a = 0111
b = 1101

b ^= a

a = 0111
b = 1010

a ^= b

a = 1101
b = 1010

I guess if a can store the difference between a and b, then b xoring itself with a will perform the first swap. But b now has the second value, so a xoring with that yields b. Cool, I didn't know it was possible to swap like that.

λ
May 11th, 2007, 12:04 PM
this is a bad idea..

http://c-faq.com/expr/xorswapexpr.html

BradLee
May 11th, 2007, 12:37 PM
^ Besides not working for an arbitrary random compiler, using a swap variable is usually FASTER than doing an XOR swap.

It's because the compiler can optimize the swap variable code to work in parallel much better. http://en.wikipedia.org/wiki/XOR_swap_algorithm