 How to Use Correct Order for C Programming Math Functions - dummies

# How to Use Correct Order for C Programming Math Functions

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

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.

`12 - 5 * 2`
`20 - 5 * 2 + 42 / 6`