[try Beta version]
Not logged in

 
*x ^= *y;

May 4, 2017 at 11:34am
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 :)
May 4, 2017 at 11:52am
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.
May 4, 2017 at 12:51pm
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.
May 4, 2017 at 1:28pm
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 :)
May 4, 2017 at 2:31pm
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 May 4, 2017 at 2:33pm
May 5, 2017 at 5:16pm
@jonnin - thanks for that ... very interesting :)
Why this is inefficient?
May 5, 2017 at 8:32pm
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 May 5, 2017 at 8:36pm
Topic archived. No new replies allowed.