DEFINITE bug in Turbo C 2.0

Daniel E. Platt platt at ndla.UUCP
Sun Mar 25 10:43:43 AEST 1990


In article <802 at zeusa.UUCP>, hendrik at zeusa.UUCP (Hendrik Vermooten) writes:
> Here is a definite bug in C (discovered by Renier v. Wyk)
> 
> (Please, no speeches about not using ++a etc in a macro :-) I've never
>  done it, and never plan to do it. Interesting bug, nonetheless)

I'm not sure why you are calling this a bug...  You see, macro's are
evaluated by the C preprocessor.  The C Compiler never see's the macros.
There's a real reason WHY people say not to use ++ operations in a
macro.  Look at this below.

> 
> #include <stdio.h>
> #define SQR(a) a*a
> main ()
> {
> 	...
> 	x = SQR (++a);
> 	y = SQR (b++);
...
...	(print the results)
...

The way that the macro is evaluated looks like

	x = ++a * ++a;
	y = b++ * b++;

With ++'s being applied twice, you don't know whether ++ will be applied
RIGHT after the first evaluation or after the whole rhs of the equation
is handled.  The standards leave this undefined.  It is just assumed that
it will never be coded.  You CAN write macros that handle these correctly
by coding so that the argument is only used ONCE.

By the way, precedence is also a possible problem with this type of
situation.  For example, if you evaluated
	
	x = SQR(a + 1);

The preprocessor would generate

	x = a + 1 * a + 1;

Which wouldn't be at all what you intended (I don't think).  The macro
should have been declared:

#define SQR(x)  ((x) * (x))

> Run by Turbo C it gives:
...(one set of answers)
> And run by Microsoft C (under XENIX):
...(another set of answers)

As a last comment, I believe that the complaint about speeches using
a++ or ++a in macros was that Hendrik was expecting an answer like
"You shouldn't do that in a macro."  The answer I gave was to explain
what macros do, and then say something like "you shouldn't use expressions
like "x = a++ * a++."  And further that macros can HIDE this.  (This is
why everyone warns against using expressions with side effects as arguments
to macros.)  Hence my presumption of saying "You should be careful when
using expressions with side effects as arguments to macros."

Hope this helps...

Dan
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
||                                     1(914)945-1173            ||
||        Dan Platt                    1(914)941-2474            ||
||        Watson (IBM)                 PLATT at YKTVMV.BITNET       ||
||                           ..!uunet!bywater!scifi!ndla!platt   ||
||                                                               ||
||     The opinions expressed here do not necessarily reflect    ||
||                   those of my employer!                       ||
||                                                               ||
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-



More information about the Comp.lang.c mailing list