C/C++ Operators#
The Basic Operations#
Like Python, C-like languages support the core mathematical operations on numerical data types, be they varables, or literals (i.e. symbols like 3
or 4.6754
). You can do any of the following:
Operator |
Operation |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
Unlike Python there is no exponentiation operator (i.e. no **
), which requires a function call instead.
Logical Operators#
Again, as with Python, all the binary logical operators below work in C/C++
Operator |
Operation |
---|---|
|
equality test |
|
greater than |
|
less than |
|
greater than or equal to |
|
less than or equal to |
|
not |
|
not equal |
|
and |
|
or |
In C++ these functions return a bool
data type which can be equal to true
or false
(note the capitalization differs from Python). However, thanks to an implicit type conversion rule, all positive integers evaluate to true and the value zero evaluates to false.
Other Useful Operators#
Operator |
Operation |
---|---|
|
increment |
|
decrement |
|
increment by |
|
decrement by |
|
remainder |
|
bitwise left shift |
|
bitwise right shift |
Operators For Completionists#
Operator |
Operation |
---|---|
|
bitwise and |
|
bitwise or |
|
bitwise xor |
|
bitwise not |
|
conditional ternary operator |
The Order of Evaluation#
There is a well defined default order of evaluation for operators in C/C++ which is worth knowing. The order of evaluation for commonly used operations is:
()
parentheses++
and--
increment and decrement*
and/
multiplication and division+
and-
addition and subtraction<<
and>>
bitwise left and right shift==
,!=
,>
,<
,>=
,<=
comparison!
not&&
and||
logical and and or=
,+=
, etc. (i.e assignment)
Summary#
We’ve now revised the basic operations which C++ allows us to apply to values in expressions, most of which have a Python equivalent. In the next section, we will look in more detail at the various control structures C++ supplies to organise, repeat or skip sections of code within a function.