Sams Teach Yourself C in 21 Days

(singke) #1
The Pieces of a C Program: Statements, Expressions, and Operators 69

4


the hours, line 23 uses the modulus operator to divide the hours and keep the remaining
minutes. Line 24 carries out a similar calculation for determining the number of seconds
that are left. Lines 26 and 27 are similar to what you have seen before. They take the val-
ues that have been calculated in the expressions and display them. Line 29 finishes the
program by returning 0 to the operating system before exiting.

Operator Precedence and Parentheses ............................................................


In an expression that contains more than one operator, what is the order in which opera-
tions are performed? The importance of this question is illustrated by the following
assignment statement:
x = 4 + 5 * 3;
Performing the addition first results in the following, and xis assigned the value 27 :
x = 9 * 3;
In contrast, if the multiplication is performed first, you have the following, and xis
assigned the value 19 :
x = 4 + 15;
Clearly, some rules are needed about the order in which operations are performed. This
order, called operator precedence,is strictly spelled out in C. Each operator has a spe-
cific precedence. When an expression is evaluated, operators with higher precedence are
performed first. Table 4.3 lists the precedence of C’s mathematical operators. Number 1
is the highest precedence and thus is evaluated first.

TABLE4.3 The precedence of C’s mathematical operators
Operators Relative Precedence
++ -- 1
* / % 2
+ - 3

Looking at Table 4.3, you can see that in any C expression, operations are performed in
the following order:


  • Unary increment and decrement

  • Multiplication, division, and modulus

  • Addition and subtraction


07 448201x-CH04 8/13/02 11:15 AM Page 69

Free download pdf