Another single-vs-double character situation occurs between logical operators (evaluating the true
/false
condition of a statement) and bitwise operators (applying mathematical combinations to numbers).
if (flag1 || flag2) { // This is a LOGICAL OR operator result = value1 | value2; // This is a BITWISE OR operator }
The compiler will rarely complain if you mix these up, because integers can be evaluated as true
(non-zero) or false
(zero).
||
is the logical OR operator, true if the operand on either side is true.
&&
is the logical AND operator, true only if operands on both sides are true.
!
is a logical NOT, which negates the operand following it. true
becomes false
and vice versa. Notice this one’s only a single character.
Bitwise, meanwhile…
|
, &
, ^
and ~
are bitwise OR, AND, XOR and NOT operators. <<
and >>
are bitwise shift operations, ensuring that we can’t make a single, all-encompassing “one versus two characters” differentiation. We’ll not go into detail of the operations themselves, already well covered elsewhere. As mentioned on the prior page, any of these can be paired up with an assignment (=
) as a shorthand operation.
Bitwise shifts have the interesting property of dividing or multiplying integers by powers of two…
a = b << 1; // Multiply by 2 a = b << 2; // Multiply by 4 a = b << 3; // Multiply by 8, etc... a = b >> 1; // Divide by 2 a = b >> 2; // Divide by 4 a = b >> 3; // Divide by 8, etc...
Old-school code often has a lot of bitwise shifts because multiply and divide were relatively costly operations at the time. But modern compilers spot this opportunity and perform such optimizations automatically if beneficial, even at “low” settings. So…if you need to divide a number by 8, just divide by 8, it reads better. In other situations bit-shifts are still very appropriate…in graphics for instance, conceptually it may be more readable to shift pixels left or right by a number of bits. All depends on the task and the idea you want to convey.
Text editor powered by tinymce.