Datasheet
will issue a warning if you assign a float to an int without an explicit cast. If you are certain that the
left-hand-side type is fully compatible with the right-hand side type, it’s okay to cast implicitly.
Operators
What good is a variable if you don’t have a way to change it? The table below shows the most common
operators used in C++ and sample code that makes use of them. Note that operators in C++ can be binary
(operate on two variables), unary (operate on a single variable), or even ternary (operate on three vari-
ables). There is only one ternary operator in C++ and it is covered in the next section, “Conditionals.”
Operator Description Usage
= Binary operator to assign the value on the right to int ;
the variable on the left. i = 3;
int j;
j = i;
!
Unary operator to negate the true/false (non-0/0) bool b = !true;
status of a variable. bool b2 = !b;
+ Binary operator for addition. int i = 3 + 2;
int j = i + 5;
int k = i + j;
-
Binary operators for subtraction, multiplication, int i = 5-1;
*
and division. int j = 5*2;
/ int k = j / i;
%
Binary operator for remainder of a division int remainder = 5 % 2;
operation. Also referred to as the mod operator.
++ Unary operator to increment a variable by 1. If the i++;
operator occurs before the variable, the result of ++i;
the expression is the unincremented value. If the
operator occurs after the variable, the result of the
expression is the new value.
-- Unary operator to decrement a variable by 1. i--;
--i;
+=
Shorthand syntax for i = i + j i += j;
-= Shorthand syntax for i -= j;
*= i = i – j; i *= j;
/= i = i * j; i /= j;
%= i = i / j; i %= j;
i = i % j;
&
Takes the raw bits of one variable and performs a i = j & k;
&=
bitwise “and” with the other variable. j &= k;
|
Takes the raw bits of one variable and performs a i = j | k;
bitwise “or” with the other variable. j |= k;
8
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 8










