*x ^= *y;

Hi there,

someone asked question about their code and he used such line of code

*x ^= *y;

I understand that this is exclusive or, but I never came across anyone using it
in code. am i missing something?

Do you use such expression as ^= or when would you use it?

thanks :)
Compound assignment operators:
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators

Many binary operators (OP) that are used: foo OP bar
might be followed by an assignment: foo = foo OP bar

Compound assignment version OP= simplifies the latter syntax: foo OP= bar

The bitwise XOR (^) is among the ones that do have ^= too.
This xor operation is often used when it comes to encryption because it can easily be undone when providing the same value the second time.

Sometimes it is also used to calculate a checksum.
thanks both

@keskiverto - yes I cam across that page on Wikipedia before, but thank you for explanation.


@coder777 - that is interesting.... I think I want to find out more :)
you can swap 2 numbers with just xor also. Its an old interview/test/useless knowledge question (its very inefficient). If you want to swap 2 things without a temporary, use the system stack or registers if you are really, really that deep into performance. Most of the time, the temporary is readable, portable, and more than fine.

If I remember it ...
a ^= b;
b^= a;
a^= b;

Last edited on
@jonnin - thanks for that ... very interesting :)
Why this is inefficient?
It does math AND copies. It does just as many assignments as the temp version, with added xor process. The temp variable costs less than the extra work, in every test I ever did.

Standard swap is coded to do it right for your data types... use that generally.
Last edited on
Topic archived. No new replies allowed.