C++ Tutorial - 06 - Operators

Uploaded by ProgrammingVideos on 14.01.2010

The numerical operators in C++ can be grouped into five types: arithmetic, assignment, comparison,
logical, and bitwise operators.
First, we have the four basic arithmetic operations, as well as modulus to get the division remainder.
Notice that the division sign gives an incorrect result here. This is because it operates on
two integer values and will therefore trunctate the result and return an integer. To get the
correct value we need to explicitly convert one of the numbers to a floating-point number.
A common use of the assignment and arithmetic operators is to operate on a variable and
then to save the result back into that same variable. These operations can be shortened
with the combined assignement operators.
Another common operation is to increment or decrement a variable by one.
This can be simplified with the increment (++) and decrement (--) operators.
Both of these can either be used before or after a variable.
The result on the variable is the same whichever we use. The difference is that the post-operator
returns the original value before it changes the variable while the pre-operator changes
the variable first and then returns the value.
Next, there's the comparison operators that compares two values and returns either true
or false.
Used together with these we have the logical operators. Logical and (&&) evaluates to true
if both the left and right sides are true, and logical or (||) is true if either the
left or right side is true. To invert a boolean result we also have logical not (!). Note
that for both "logical and" and "logical or" the righthand side won't be evaluated if the
result is already determined by the left side.
Lastly, we have the bitwise operators which allow us to manipulate individual bits inside
of an integer. For example, the or operator (|) makes the
resulting bit 1 if the bits are set on either side of the operator. These bitwise operators
also have shorthand assigment operators.
Now, let's look at operator precedence. In C++ expressions are normally evaluated from
left to right. However, as can be seen in this table different operators also have different
precedents that determine which one gets evaluated first. This same order also applies to many
other languages such as Java and C# also. As an example, the logical and operator binds
weaker than the relational operators, which in turn binds weaker than the arithmetic operators.
To make things clearer we should instead use parenthesis to decide what part of the expression
will be evaluated first since parenthesis has the highest precendence of all operators.