You're viewing a comment by Mattho and its responses.

July 01, 2009, 13:53

Another bit-based operation:
Switch values of a and b w/o using additional variable

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

Comment Responses

anonym Permalink
April 19, 2011, 12:38

This is undefined behaviour (i.e. implementation dependent) in C/C++ and it doesn't work in Java.

Partho Permalink
February 25, 2012, 03:48

here you go: a=a^b; b=a^b; a=a^b;

William Swartzendruber Permalink
June 13, 2014, 20:55

This could play hell with the CPU's pipeline. I think the best way to go is to simply use a temporary register.

anon Permalink
April 18, 2016, 05:39

try it when a == b :)

January 08, 2017, 00:19

It works fine when a == b. That you could think it wouldn't indicates that your math intuitions are bad.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "computer_143": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.