Game Development Reference
In-Depth Information
Listing 3-13. The Increment and Decrement Operators
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int value = 0;
cout << value << endl;
cout << value++ << endl;
cout << ++value << endl;
cout << value-- << endl;
cout << --value << endl;
return 0;
}
The output from this program is the following:
0
0
2
2
0
We achieve this in the following way. 0 is output in the first
cout
line as the variable value was
initialized to 0. The second
cout
also prints 0 as the postincrement operator returns the value of the
variable, then increases it; therefore, we print out 0 then add 1. The third
cout
uses a preincrement
operator; therefore, 1 is added to the variable, giving 2, which is then returned to
cout
for printing.
Our fourth
cout
uses a post decrement operator that causes the value 2 to be returned from the
variable before it is decremented to 1. The last
cout
decrements the variable to 0 before returning it
to the
cout
command for printing.
These operators will be useful when we look at arrays in Chapter 4.
The Logical Not Unary Operator
Logical Not allows us to flip the value of a boolean value. Using
!
,
true
becomes
false
and
false
becomes
true
. We could determine if two values were not equal in the following way:
bool notEqual = !(valueA == valueB);
This is a simple example of how to use the
!
operator.
The One's Complement Operator
The operator,
~
, can be used to flip all of the bits in a variable. Listing 3-14 shows a program to
print the output from the
~
operator.