Operators#

C++ defines a lot of operators that can be used on objects. We’ll discuss them here in the context of math with numeric types, but these operators can be extended to work with other types as well.

Mathematical operators#

The standard mathematics operators are:

  • + : addition

  • - : subtraction

  • * : multiplication

  • / : division

  • % : modulus

In addition, + and - can be used as unary operators, e.g., to negate a quantity:

double x = -y;

Relational operators#

Assignment operators#

Precedence#

What happens when we have an expression like:

a + b * c;

The language defines the order that operators are considered, called operator precedence.

This table: C++ Operator Precedence lists the order in which operators are evaluated.

In the example above, multiplication has higher precedence, so it is evaluated first, and then the addition is done.

Tip

We can use parentheses to force a group to be evaluated first, e.g., (a + b) * c

Try it…

Play around with some expressions to explore the precedence of operators.

Prefix and postfix operators#

We haven’t yet discussed the difference between ++a and a++. These are the prefix and postfix increment operators. Let’s do that now.

The prefix operator is:

int a{0}, b{0};
b = ++a;

The prefix increment operator first increments the value of the object and then returns a reference to the result. So in the above example, the result would be b = 1.

Now consider the postfix operator:

int c{0}, d{0};
d = c++;

Here, a copy of c is made, then c is incremented, and finally the copy is returned. So in the above example, the result would be d = 0.

Tip

The behavior of the prefix and postfix operator is essentially the same when it is on its own line. Also in the for construction:

for (int i = 0; i < 10; ++i) {
    ...

it doesn’t matter much which version you use—although you will commonly see the prefix version used since it does not make a copy, and therefore can be faster.

Associativity#

When an expression has two operators at the same precedence, operator associativity rules come into play. Most operators in C++ are left associative—that is, they are grouped from the left, but some are right associative (like the unary operators and assignment) meaning that they are grouped from the right.

Consider assignment:

a = b = c

Since = has right associativity, we interpret this as a = (b = c), which can further be thought of as b = c; a = c.

Note

In C++, assignment evaluates to the left value.

In the expression:

a + b - c

Both + and - have the same precedence, and these are left-associative, so first a + b is evaluated and then c is subtracted from that result.