Section 6 - Numeric Expressions and Operators
2A.6.1 Expressions
All of the stuff on the RHS (right hand side) of the = sign is called an expression - a conglomeration of numbers, operators and other things that evaluates to a single number. The number to which that expression evaluates is what gets stored into the variable location named on the LHS (left hand side):
n = 3 * (2 + b) * (tree - 1);
Here, b and tree are assumed to be variables (or objects). Their values are retrieved from memory and plugged into the expression. If b happened to have a 5 stored in it, and tree, a 0, then the expression would evaluate to
3 * (2 + 5) * (0 - 1) → 3 * 7 * (-1) → -21.
Notice two things:
- The spaces don't matter in expressions. Remember, whitespace that lives outside quotes is irrelevant to the program, even if it is important for human readability.
- The parentheses are sometimes needed, other times just put in for clarity of reading. This depends on what is called operator precedence.
You will lose points if you use a single letter variable name in most situations. You see me using single letter names here because I am trying not to confuse you with words in these early examples. However, in actual practice and in your assignments you would use names like basePrice instead of b, or age instead of n. The name of the variable should reflect what role it plays in your program. In other words, someNumber is probably not a good variable name.
2A.6.2 Numeric Operators and Precedence
There are many numeric operators in C++. Addition (+), subtraction (-), multiplication (*), division (/) and modulo (%) are just a few of the obvious ones. There is no exponentiation operator in C++. You have to perform exponentiation using a pow() method in the math library <cmath>, but I don't want you doing that yet. So, if you need an exponent, you'll have to do it with repeated multiplications.
If you have a number with an operator on each side, like
dog + tree * cat
then the two operators are vying for the same variable object, tree in this case. So which operator gets tree's attention first? Since multiplication, *, has a higher precedence than addition, +, it is computed first.
If two operators have equal precedence, usually the one on the left is executed before the one on the right. I will mention exceptions when they come up.
So if we don't use parentheses, then
2+3 * 5
will evaluate to 17, not 25. If you want it otherwise, write it as such:
(2+3) * 5
Besides remembering that * and / have equal precedence and both have greater precedence than + and -, I personally don't remember the precedence of most operators. That's what the parentheses are for. When in doubt, use them to group your expressions.
For the moment, we will only consider expressions that have int variables and constants in them. Soon we will deal with "mixed mode" arithmetic: expressions containing varying data types, i.e. other types of data besides int.
