? :
is sort of like an
if/then
statement, only it's an expression.
A ? B : C
will evaluate A. Then if A is true (or non-zero) then it evaluates B, otherwise it evaluates C. The value of the expression is the value of B or C, whichever was evaluated.
For example:
1 2 3
|
bool b;
// do something that sets b;
cout << "b is " << (b ? "true" : "false") << end;
|
This will print "bis is true" or "b is false"
Since an expression can have only one type, B and C must be the same type, or be convertable to the same type.
I use
? :
frequently. In particular, instead of
1 2 3 4 5
|
if (condition) {
var = expr1;
} else {
var = expr2;
}
|
I usually write
var = (condition ? expr1 : expr2);
<<
and
>>
were originally the bit shift operators in C.
a << 2
takes the bits in a and shifts them all up 2 positions, filling the least significant bits with 0. For example
4 << 2
== 16. Similarly
b >> 2
shifts the bits down two positions. The most significant bits are filled with zeros or replicas of the sign bit, depending on whether the original value was unsigned or signed.
But in C++ you can overload operators, so it's more frequent to see << and >> used for I/O with streams.
istream >> var
will read var from istream, and
ostream << var
will put var into ostream.