Re: 'C' Operators precedence

Oliver Xymoron (oxymoron@waste.org)
Thu, 21 May 1998 14:50:57 -0500 (CDT)


On 20 May 1998, H. Peter Anvin wrote:

> This is just plain WRONG. The C standard is very explicit that there
> are no sequence points between the evaluation of the arguments of
> addition; in fact, only a few operators have any serialization
> property; && and || does, and maybe (I am not sure about this one) the
> assignment operators.

>From K&R 2e, 2.12:

C, like most languages, does not specify the order in which the
operands of an operator are evaluated. (The exceptions are &&, ||,
?:, and ',') For example, in a statement like

x = f() + g();

f may be evaluated before g or vice versa;

As for assignment operators, if you had a statement like

int *e(void);
int f(void);
int g(void);

*e() = f() + g();

the compiler would be free to call e, f, and g in any order. If the
address that e() returned was order-dependent to f and g, you'd be in
trouble.

Note that the comma operator is the rather rare one in the statement

return foo(), bar(); /* Call foo, then return bar */

and not the one in

foo(a, b);

ps: I relearned this lesson recently when I wrote a driver routing that
did something like

return getbyte(addr)+(getbyte(addr)<<8); // build a word from next 2 bytes

which Did What I Meant on one of the compilers we were using but the
opposite thing on another.

--
 "Love the dolphins," she advised him. "Write by W.A.S.T.E.." 

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu