This one bit me today

Lars P. Fischer fischer at iesd.auc.dk
Sun Oct 8 06:36:17 AEST 1989


In article <832 at crdos1.crd.ge.COM> davidsen at crdos1.crd.ge.COM (Wm E Davidsen Jr) writes:
>  It pops up in macros from time to time. Consider:
>	#define xavg(m) (sum+3)/m

>From K&R, 2.ed, p.90:

    Some care also has to be taken with parentheses to make sure the
    order of evaluation is preserved.

>From Harbison & Steele, 2.ed., p. 36:

    As a rule, it is safest always to parenthesize each parameter
    appearing in the macro body. The entire body, if it is
    syntactically an expression, should also be parenthesized.

(The whole page is used by section 3.3.6 "Precedence errors in macro
expansion").

So, what do we learn. Well, the above should have been:

	#define xavg(m) ((sum+3) / (m))

Hopefully, we also learn that any C programmer worth his salt knows
K&R by heart, and has H&S handy :-).

> It's even worse if someone makes a mistake like this in a system
>header file...

If you don't know how to use CPP you shouldn't be allowed to write
system header files.

/Lars
--
Copyright 1989 Lars Fischer; you can redistribute only if your recipients can.
Lars Fischer,  fischer at iesd.auc.dk, {...}!mcvax!iesd!fischer
Department of Computer Science, University of Aalborg, DENMARK.

"That makes 100 errors; please try again" --TeX



More information about the Comp.lang.c mailing list