Start learning free

LESSON 19 OF 409 · CALCULATIONS WITH NUMBERS

Operator Precedence in C++

Lesson

TL ; DR:

  • When we string operations together, C++ must know which one to do first. This is called operator precedence.


  • * and / are performed before + and -:

  • cout << 1 + 2 * 3; // Prints 7
    cout << 6 - 4 / 2; // Prints 4
    cout << 5 * 4 - 2 / 2; // Prints 19
    

  • We can add () to force an operation to be performed first:

    cout << (1 + 2) * 3; // Prints 9
    cout << (6 - 4) / 2; // Prints 1
    cout << 5 * (4 - 2) / 2; // Prints 5
    


Full lesson:

When we string operations together, C++ must know which one to do first. This is called operator precedence.

This is the hierarchy from highest precedence to lowest precedence:

  • Parentheses are always respected
  • Exponentiation (raise to a power)
  • Multiplication, Division and Remainder
  • Addition and Subtraction
  • Left to right


First example:

cout << 1 + 2 * 3; // Output: 7

Multiplication is executed before addition, so:

1 + 2 * 3 = 1 + 6 = 7

Second example:

cout << (1 + 2) * 3; // Output: 9

What's inside parentheses is executed before multiplication, so:

(1 + 2) * 3 = 3 * 3 = 9

Third example:

cout << 6 / 4 * 3 + 5; // Output: 9.5

Multiplication and division come before addition. Also, multiplication and division have the same priorty so they are executed from left to right:

6 / 4 * 3 + 5 = 1.5 * 3 + 5 = 4.5 + 5 = 9.5

Forth example:

cout << 6 / ((4 + 2) / 3); // Output: 3

Computer sees parentheses so it looks at it like this:

6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3

I have to compute x first. Parantheses are executed before division:
(4 + 2) / 3 = 6 / 3 = 2

I can replace x with 2:
6 / ((4 + 2) / 3) = 6 / 2 = 3


Assignment
Follow the Coding Tutorial and let's practice with operator precedence!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check