HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 5 Expressions and Operators

Evaluation of Expressions

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Expressions are evaluated at run time. The results of the evaluation are called by product values. For many expressions, you won't know or care what this byproduct is. In some expressions, though, you can exploit this feature to write more compact code.

Examples

The following expression is an assignment.

x = 6;

The value 6 is both the byproduct value and the value that gets assigned to x. The byproduct value is not used.

The following example uses the byproduct value:

y = x = 6;

The equals operator binds from right to left; therefore, C first evaluates the expression x = 6. The byproduct of this operation is 6, so C sees the second operation as

y = 6

Now, consider the following relational operator expression:

(10 < j < 20)

It is incorrect to use an expression like this to find out whether j is between 10 and 20. Since the relational operators bind from left to right, C first evaluates

10 < j

The byproduct of a relational operation is 0 if the comparison is false and 1 if the comparison is true.

Assuming that j equals 5, the expression 10 < j is false. The byproduct will be 0. Thus, the next expression evaluated:

0 < 20

is true (or 1). This is not the expected answer when j equals 5.

Finally, consider the following fragment:

static char a_char, c[20] = {"Valerie"}, *pc = c;

while (a_char = *pc++) {
. . .

This while statement uses C's ability to both assign and test a value. Every iteration of while assigns a new value to variable a_char. The byproduct of an assignment is equal to the value that gets assigned. The byproduct value will remain nonzero until the end of the string is reached. When that happens, the byproduct value will become 0 (false), and the while loop will end.

Evaluation Order of Subexpressions

The C language does not define the evaluation order of subexpressions within a larger expression except in the special cases of the &&, ||, ?:, and , operators. When programming in other computer languages, this may not be a concern. C's rich operator set, however, introduces operations that produce side effects. The ++ operator is a prime example. The ++ operator increments a value by 1 and provides the value for further calculations. For this reason, expressions such as

b = ++a*2 + ++a*4;

are dangerous. The language does not specify whether the variable a is first incremented and multiplied by 4 or is first incremented and multiplied by 2. The value of this expression is undefined.

© Hewlett-Packard Development Company, L.P.