C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
figure shows, you should compute one operator at a time and then bring the rest of the
expression down for the next round.

If an expression such as the one in Figure 9.1 contains more than one operator that sits on the same
level in the order of operators table, you must use the third column, labeled Associativity, to
determine how the operators are evaluated. In other words, because *, /, and % all reside on the
same level, they were evaluated from left to right, as dictated by the order of operators table’s
Associativity column.


You might wonder why you have to learn this stuff. After all, doesn’t C do your math for you? The
answer is “Yes, but....” C does your math, but you need to know how to set up your expressions
properly. The classic reason is as follows: Suppose you want to compute the average of four
variables. The following will not work:


Click here to view code image


avg = i + j + k + l / 4; /* Will NOT compute average! */

The reason is simple when you understand the order of operators. C computes the division first, so l
/ 4 is evaluated first and then i, j, and k are added to that divided result. If you want to override
the order of operators, as you would do in this case, you have to learn to use ample parentheses
around expressions.


Break the Rules with Parentheses


If you need to override the order of operators, you can. As demonstrated in Table 9.1, if you group an
expression inside parentheses, C evaluates that expression before the others. Because the order of
operators table shows parentheses before any of the other math operators, parentheses have top
precedence, as the following statement shows:


Click here to view code image


ans = (5 + 2) * 3; /* Puts 21 in ans */

Even though multiplication is usually performed before addition, the parentheses force C to evaluate
5 + 2 first and then multiply the resulting 7 by 3. Therefore, if you want to average four values, you
can do so by grouping the addition of the values in parentheses:


Click here to view code image


avg = (i + j + k + l) / 4; /* Computes average */

Tip

Use lots of parentheses. They clarify your expressions. Even if the regular operator
order will suffice for your expression, parentheses make the expression easier for you
to decipher if you need to change the program later.

Assignments Everywhere

Free download pdf