How to Use Correct Order for C Programming Math Functions

By Dan Gookin

Before you flee the tyranny of the Unavoidable Math, you need to know about the order of precedence for C programming. It’s not a religious order, and it has nothing to do with guessing the future. It’s about ensuring that the math equations you code in C represent what you intend.

How to get the order correct

Consider the following puzzle. Can you guess the value of the variable answer?

answer = 5 + 4 * 3;

As a human, reading the puzzle from left to right, you’d probably answer 27: 5 + 4 is 9 times 3 is 27. That’s correct. The computer, however, would answer 17.

The computer isn’t wrong — it just assumes that multiplication is more important than addition. Therefore, that part of the equation gets calculated first. To the computer, the actual order of the values and operators is less important than which operators are used. To put it another way, multiplication has precedence over addition.

You can remember the basic order of precedence for the basic math operators like this:

First: Multiplication, Division

Second: Addition, Subtraction

The clever mnemonic for the basic order of precedence is, “My Dear Aunt Sally.” For more detail on the order of precedence for all C language operators, see Appendix G.

Exercise 1: Write a program that evaluates the following equation, displaying the result:

20 - 5 * 2 + 42 / 6

See whether you can guess the output before the program runs.

Exercise 2: Modify the code from Exercise 1 so that the program evaluates the equation

12 / 3 / 2

No, that’s not a date. It’s 12 divided by 3 divided by 2.

How to force order with parentheses

The order of precedence can be fooled by using parentheses. As far as the C language is concerned, anything happening within parentheses is evaluated first in any equation. So even when you forget the order of precedence, you can force it by hugging parts of an equation with parentheses.

Math ahead!

Exercise 3: Code the following equation so that the result equals 14, not 2:

12 - 5 * 2

Exercise 4: Code the following equation (from Exercise 1) so that addition and subtraction take place before multiplication and division. If you do it correctly, the result is 110:

20 - 5 * 2 + 42 / 6
  • In the future, the code you write may deal more with variables than with immediate values, so you must understand the equation and what’s being evaluated. For example, if you need to add the number of full-time and part-time employees before you divide by the total payroll, put the first two values in parentheses.

  • Beyond the order of precedence, parentheses add a level of readability to the code, especially in long equations. Even when parentheses aren’t necessary, consider adding them if the result is more readable code.