I have some code that performs a bitwise XOR operation (^
) on two variables and adds the result to a third variable.
Turns out that the following two statements produce different results:
checksum += digit ^ (2 * checksum); //correct result
checksum = checksum + digit ^ (2 * checksum); //incorrect result
Why is that so?
(Edit: I changed the question to specifically target the issue that was causing problems with my program.)
This expression
checksum = checksum + digit ^ (2 * checksum);
is evaluated like
checksum = ( checksum + digit ) ^ (2 * checksum);
because the Bitwise exclusive OR operator ^
has a lower priority than the additive operator +.
This expression
checksum += digit ^ (2 * checksum);
is evaluated like
checksum = ( checksum ) + ( digit ^ (2 * checksum) );
That is in this compound assignment operator
checksum += digit ^ (2 * checksum);
the expression digit ^ (2 * checksum)
is evaluated and added to the value of checksum
.
From the C++ 17 Standard (8.5.18 Assignment and compound assignment operators)
7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.
So there are two expressions E1
and E2
that are evaluated and then the binary operator op
is applied to them.