INF:Precedence Affects How Operands are Grouped, Not Evaluated

ID Number: Q37624

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

Precedence in C means how operands are grouped, not necessarily the

order in which they will be evaluated. Note that logical AND (&&) has

a higher precedence than logical OR (||). The statement

lvalue = operand1 || operand2 && operand3;

will be grouped as follows:

lvalue = operand1 || (operand2 && operand3);

However, this does not mean (operand2 && operand3) will be evaluated

first in the above statement. In fact, this statement is a logical OR

expression with two operands: operand1 and (operand2 && aoperand3).

Operands are defined as an entity on which an operator acts; in this

case the logical OR operator || acts on operand1 and (operand2 &&

operand3). Logical OR expressions are evaluated in left-to-right

order, so operand1 will be evaluated first.

The following example demonstrates this behavior:

Sample Code:

------------

/* Compile options needed: none

*/

#include <stdio.h>

int a,b,c,d;

void main()

{

a = (b = 2) || (c = 3) && (d = 4);

printf( "a = %d, b = %d, c = %d, d = %d\n", a, b, c, d );

}

Program output:

a = 1, b = 2, c = 0, d = 0

Because (b = 2) is not 0, no further evaluations are performed, and c

and d are not assigned 3 and 4. If the intent is to assign values to

variables, then separate assignment statements should be made.

As noted in "The C Programming Language" by Kernighan and Ritchie

(second edition), page 54, "The moral is that writing code that

depends on the order of evaluation is a bad programming practice in

any language."

Additional reference words: 5.10 6.00 6.00a 6.00ax 7.00