|
|
C++ tutorial: operator reference
Operator reference
These tables list the most commonly used C++ operators
Arithmetic operators
|
+
|
Plus
|
|
|
-
|
Minus
|
can be used in 'unary' format, e.g., '-x'
|
|
*
|
Multiply
|
|
|
/
|
Divide
|
|
|
%
|
Modulus
|
'x % y' is the remainder when x is divided by y
|
Bitwise operators
These operate on the individual binary bits in a variable or expression.
|
&
|
bitwise AND
|
'x & y' means the result of the bitwise AND operation applied to x and y
|
|
|
|
bitwise OR
|
'x | y' means the result of the bitwise OR operation applied to x and y
|
|
^
|
bitwise XOR
|
'x ^ y' means the result of the bitwise XOR operation applied to x and y
|
|
~
|
bitwise NOT
|
'~x' means the result of the bitwise NOT operator applied to each of the bits of x
|
Assignment operators
These are used to assign values to, or directly modify, the value
of a variable
|
=
|
equal
|
'x = y' means 'set x to the same value as y'
|
|
++
|
increment
|
If ++ is applied to a number variable, it simply adds one to the variable's
value. There are two alternative representations: x++ (called 'post-increment') and
++x (called pre-increment). If 'x++' is a statement on its own pre- and post-increment
instructions have exactly the same effect. If 'x++' is part of a larger expression
being evaluated, pre-increment cause the value to be incremented before the
expression is evaluated, while post-increment causes the increment to come after
evaluation. In my opinion, a program is easier to understand if it is written in
such a way that pre-increment and post-increment would be identical. This saves
the reader needing to work out the order in whcih things happen.
|
Note that all the arithmetic and bitwise operators can also be assignement
operators, simply by appending the '=' sign to the symbol. For example, 'x += 2'
means 'add two to x'. '+=' is usually read "plus and becomes". However, the use
of these symbols, while often very concise, can cause difficulty for a person
trying to understand the program; use with caution.
Logical operators
|
&&
|
and
|
'x && y' is true if both x and y are true
|
|
||
|
or
|
'x || y' is true if either x or y is true, or both are
|
|
!
|
not
|
'!x' is true if either x is not true
|
Comparison operators
|
==
|
Equal
|
'x == y' is true if x is equal to y
|
|
!=
|
Not equal
|
'x != y' is true if x is not equal to y
|
|