[Bug preprocessor/38179] need a warning: macro parameter is not a whole expression within macro body

mlg7 at yandex dot ru gcc-bugzilla@gcc.gnu.org
Fri Nov 21 08:45:00 GMT 2008



------- Comment #2 from mlg7 at yandex dot ru  2008-11-21 08:44 -------
(In reply to comment #1)
> The expanded text for the first one is:
> int t = 1|2 & 0xFFFFFF00 ? dothis(1|2) : dothat(1|2);
> 
> Maybe I am missing something here. 
> 
the human who is writing
int t = MYMACRO(FLAGA|FLAGB);
obviously means
int t = (1|2) & 0xFFFFFF00 ? dothis(1|2) : dothat(1|2); // #1
while the compiler treats this as
int t = 1|(2 & 0xFFFFFF00) ? dothis(1|2) : dothat(1|2); // #2

(google for "C Operator Precedence" if you need to check it)

This is a well-known preprocessor gotcha. I propose to add a warning for such
cases.

PS

That is, there are two gotchas: the problem with expressions as macro
parameters and the same problem with expressions in generated text. The Clever
Books tell folks to enclose all macro parameters in parens and enclose the
whole macro body in parens.

So, the recommended way for writing
#define MYMACRO(x) x & 0xFFFFFF00 ? dothis(x) : dothat(x)
is
#define MYMACRO(x) ((x) & 0xFFFFFF00 ? dothis((x)) : dothat((x)))

It looks like LISP but it works. But practice shows that not everybody reads
The Clever Books...


-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38179



More information about the Gcc-bugs mailing list