Arithmetic Operators and Expressions

x + y

x + y is the sum of x and y.

xy

xy is the difference, xy.

x

x is the negation of x.

x * y

x * y is the product x times y.

x / y

x / y is the quotient x divided by y.

Important: If x and y are both integers then x/y is also an integer. Anything after the decimal point is ignored. So 7/4 has value 1, not 1.75.

C++ uses the integer division that you learned before you learned about decimal points. Suppose

  1. you have 14 apples to share among 3 children,
  2. each child must receive the same number of apples,
  3. you are not allowed to cut an apple and
  4. you must distribute as many apples as possible among the 3 children.

Then each child gets 4 apples and 2 apples are left over. So 14/3 = 4 and 14%2 = 2.


x % y

x % y is the remainder when you divide integer x by integer y. For example, when you divide 14 by 3 you get a quotient of 4 and a remainder of 2. So 14 % 3 = 2. You can only use the % operator on integers.


Precedence and associativity

Operator * has higher precedence than operator +. For example, expression 2 + 5 * 2  has value 12, since the multiplication is done first.

Use parentheses to override precedence rules. Expression (2 + 5) * 2  has value 14.

Operators *, / and % have the same precedence, and binary operators + and - have the same precedence. The negation operator has highest precedence, even higher than *.

All of the numeric operators are performed from left to right, except where precedence rules and parentheses force otherwise. For example, 10 − 2 − 3  has value 5, but 10 − (2 − 3) has value 11.

Notice that 16/2*2 has value 16 since * and / have the same precedence. The division 16/2 is done first, and then the result of that division is multiplied by 2. If you want 16/(2*2), be sure to use parentheses.


Conversions between numeric types

Automatic conversions

Numbers are converted automatically from one type to another where necessary. For example, 2 is converted to 2.0 if it occurs where a value of type double is needed.

When one operand of a binary operator is an integer and the other is a real number, the integer is automatically converted to a real number.

Converting an integer to a real number is usually harmless. Converting a real number to an integer throws away everything after the decimal point. So if 2.7 occurs in a place where an integer is required, it is converted to 2. Watch out for that. It can lead to errors that are difficult to detect, where you accidentally use type int but mean double.

Explicit conversions

You can request conversions explicitly. If T is a numeric type, then write (T) in front of an expression to convert the value of that expression to type T. For example, expression (int)(x + y ) is the value of x + y converted to type int.