Game Development Reference
In-Depth Information
The Right Shift (>>) Operator
The right shift operator carries out the opposite operation to the left shift operator.
unsigned int shifted = 0x2 >> 1;
shifted contains 1 after executing this line of code. Again, if you shift values off the end then they
are lost.
There is a significant difference between the left and right shift operators. When left shifting, all of the
new values are set to 0. When right shifting the new bits depend on whether your value is a signed or
unsigned type. Unsigned types have the values at the left of the bit pattern set to 0. Signed types have
these set to the value contained in the sign bit. This means that positive values will have these bits set to
0 and negative values will have these bits set to 1. If you're having trouble remembering why this would
be, you should go back over the description of twos complement numbers in the previous chapter.
Bitwise operators can be fairly complex to get your head around, but they can be a very powerful
tool for a programmer. The next set of operators that we will be looking at is the logical operators.
Logical Operators
We are going to cover logical operators here without covering any source examples. Logical
operators are at their most useful when combined with flow control statements, which we will look
at in Chapter 6. There are two logical operators: Logical AND ( && ) and Logical OR ( || ). These behave
differently to the Bitwise & and | operators, so it is critical that you ensure that you are choosing the
appropriate operator for the task at hand.
Logical operators operate on two boolean values and return a boolean result.
The && Operator
The && operator simply tells us whether two booleans are both true. For example:
bool isTrue = true && true;
bool isFalse = false && true;
bool isFalse = true && false;
bool isFalse = false && false;
bool isTrue = true && true && true;
There isn't any more to the && operator than this.
The || Operator
The || operator is as simple as the && operator. Some results when using || are as follows:
bool isTrue = true || true;
bool isTrue = false || true;
bool isTrue = true || false;
bool isFalse = false || false;
bool isTrue = true || false || false;
 
Search WWH ::




Custom Search