Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

# what does k^=k; means in c++?

I'm trying to understand a c++ code. There is a "for cicle" that has this form: for (k^=k; k < limit; ++k, num <<= 1). I can see the different values for k on the screen just by using printf( "k"); k^=k starts at zero accordingly. The thing is that I don't understand why. Thanks so much in advice. (note: k is of type int).

Category

### 2 Answers

Relevance
• Favorite Answer

^= is of ^ what += is of +

^ is the bitwise xor operator. It does an 'exclusive or', defined as

0^0 = 0

1^0 = 1

0^1 = 1

1^1 = 0

Note the difference with every day 'or' that would give a 1 on the last line. Special about xor is the symmetry. You can take the result and one of the two input values on the four equations above and get the other input value.

No matter what value k has, it will have a value of all zeros after k = k^k (which is the same as k^=k). I do not see why anyone would want to do it in this elaborate way.

• It's another, possibly misguided way of initializing k to 0. Whoever wrote that probably realizes that loading four bytes of zeros from memory into a register is less efficient than other ways of zeroing the register, and knows that xoring the register with itself is faster. But compilers know this too and would have generated the best code for initializing k to 0, without the confusion.

Still have questions? Get your answers by asking now.