Datasheet
Operator Description Usage
<< Takes the raw bits of a variable and “shifts” each i = i << 1;
>>
bit left (<<) or right (>>) the specified number of i = i >> 4;
<<=
places. i <<= 1;
>>= i >>= 4;
^
Performs a bitwise “exclusive or” operation on i = i ^ j;
^=
the two arguments. i ^= j;
The following program shows the most common variable types and operators in action. If you’re unsure
about how variables and operators work, try to figure out what the output of this program will be, and
then run it to confirm your answer.
// typetest.cpp
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int someInteger = 256;
short someShort;
long someLong;
float someFloat;
double someDouble;
someInteger++;
someInteger *= 2;
someShort = (short)someInteger;
someLong = someShort * 10000;
someFloat = someLong + 0.785;
someDouble = (double)someFloat / 100000;
cout << someDouble << endl;
}
The C++ compiler has a recipe for the order in which expressions are evaluated. If you have a compli-
cated line of code with many operators, the order of execution may not be obvious. For that reason, it’s
probably better to break up a complicated statement into several smaller statements or explicitly group
expressions using parentheses. For example, the following line of code is confusing unless you happen
to know the C++ operator precedence table by heart:
int i = 34 + 8 * 2 + 21 / 7 % 2;
Adding parentheses makes it clear which operations are happening first:
int i = 34 + (8 * 2) + ( (21 / 7) % 2 );
9
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 9










