32 Chapter 4 Variables, Data Types, and Arithmetic Expressions
On some computer systems, attempting to divide a number by zero results in abnor-
mal termination of the program.^2 Even if the program does not terminate abnormally,
the results obtained by such a division will be meaningless.
In Chapter 6, you see how you can check for division by zero before the division
operation is performed. If it is determined that the divisor is zero, an appropriate action
can be taken and the division operation can be averted.
The expression
a + b * c
does not produce the result of 2550 (102 ×25); rather, the result as displayed by the cor-
responding printfstatement is shown as 150.This is because C, like most other pro-
gramming languages, has rules for the order of evaluating multiple operations or terms in
an expression. Evaluation of an expression generally proceeds from left to right.
However, the operations of multiplication and division are given precedence over the
operations of addition and subtraction.Therefore, the expression
a + b * c
is evaluated as
a + (b * c)
by the C system. (This is the same way this expression would be evaluated if you were to
apply the basic rules of algebra.)
If you want to alter the order of evaluation of terms inside an expression, you can use
parentheses. In fact, the expression listed previously is a perfectly valid C expression.
Thus, the statement
result = a + (b * c);
could have been substituted in Program 4.2 to achieve identical results. However, if the
expression
result = (a + b) * c;
were used instead, the value assigned to resultwould be 2550 because the value of a
( 100 ) would be added to the value of b( 2 ) before multiplication by the value of c( 25 )
would take place. Parentheses can also be nested, in which case evaluation of the expres-
sion proceeds outward from the innermost set of parentheses. Just be certain you have as
many closed parentheses as you have open ones.
You will notice from the last statement in Program 4.2 that it is perfectly valid to give
an expression as an argument to printfwithout having to first assign the result of the
expression evaluation to a variable.The expression
a * b + c * d
2.This happens using the gcccompiler under Windows. On Unix systems, the program might
not terminate abnormally, and might give 0 as the result of an integer division by zero and
“Infinity” as the result of a floatdivision by zero.