2. First Programs
Operators and Priority
C++ enables us to employ all the basic arithmetic operations: addition, subtraction,
multiplication and division, by using conventional symbols (+
, -
, *
, /
). The
star symbol, also known as the asterisk, is the
multiplication operator while the forward slash
is the division operator. For these
operators, normal arithmetic priorities apply: multiplication and division
operators have higher priority than addition and subtraction operators.
Therefore, the program
int main() { cout << 20-3*4; }
results with:
STDOUT: 8
Because the multiplication operator has priority over the subtraction operator, the evaluation of expression 3*4 is performed before subtraction.
An operator is just a symbol that represents an operation. In C++ and most other programming languages, operators are special because each one has a specific and predetermined meaning in the grammar of the language.
It is entirely possible to compute multiple expressions by a single statement:
int main() { cout << 7+5 << 20/5; }
The given program outputs the following:
STDOUT: 124
Where did this number 124 suddenly come from? It is quite simple: 7+5 equals 12 and 20/5 equals 4. Therefore, first the number 12 has been written out, followed by the number 4. That just looks like the number 124 because we have not separated the two numbers by any delimiters. We can separate them by using a string containing just a single space character:
cout << 7+5 << " " << 20/5;
This statement results with the following output:
STDOUT: 12 4