I am bit confused about a expression I found in some C++ code:
if (m & 1)
pmm=-pmm;
I am not a C/C++ coder, so Google gives me two things:
- & is bitwise AND
if
syntax isif (condition) statement
So, how does the above statement work?
Should I not require a if ((m & 1)==0)
?
m will be represented in memory as a binary number, in other words: a series of bits. The value 1 will also be represented as a series of bits.
For example (I have chosen 8 bit length for simplicity):
Performing a bitwise operation on m will perform the operation you specify, in this case & (AND) on each bit at the same position on each binary number on either side of the & symbol.
i.e. Bit 1 of result = Bit 1 of m & Bit 1 of the value 1. Bit 2 of result = Bit 2 of m & Bit 2 of the value 1 etc...
So for our example:
Assuming m is an integer, the bitwise operation will return an integer. The if statement will check if the result is true, and since it is an integer it will be interpreted as true if non-zero.
The result is not zero hence it will return true in our example.
So: By AND-ing an integer with 1 you will end up returning true in your code for odd numbers only, since bit 1 is always 1 for odd numbers.
Just to add to the more technical explanations, a simpler way of viewing
if (m & 1)
is that is tests whetherm
is odd (i.e. not an exact multiple of 2):This is bitwise AND operator. m & 1 evaluates to 1 if bit 0 is set and every expression that is not 0 is true implicitly.
Following are equivalent expressions:
However caution is required if testing more bits. For example m = 1:
if (m & 3)
istrue
also, but the result is1
. Better isif ((m & 3) == 3)
in this case.