macros w/o side effects (was Re: declarations in include files)

Tom Stockfisch tps at chem.ucsd.edu
Tue May 16 15:45:07 AEST 1989


In article <8420 at phoenix.Princeton.EDU> bernsten at phoenix.Princeton.EDU (Dan Bernstein) writes:
#In article <2337 at mit-caf.MIT.EDU> vlcek at mit-caf.UUCP (Jim Vlcek) writes:
## In article <181 at larry.sal.wisc.edu> jwp at larry.sal.wisc.edu.UUCP
##   You know the tune:
## #define square(x) ((x)*(x))  /* Used to be a function ... needed speed */
## y = square(++i);
## Any macro->function sleight of hand had best not take place behind the
## scenes, and in fact should probably not take place at all....

#I even take functions like
#
#  sqaure(in,out) int in; int *out; { *out = in * in; }
#
#and convert them into macros like
#
#  #define square(in,out) { int Tsquare1 = in; int *Tsquare2 = out;
#			   *Tsquare2 = Tsquare1 * Tsquare1; }
#
#Gasp! Where's the error when I do square(i++,&result)? Where have the
#side effects gone? How come this macro does exactly the same thing as
#the function except that it's faster? And I would have thought from the
#above article that this was impossible!
#There are no side effects, it's all perfectly safe, and I don't think
#I deserve to suffer for it.



Well, it's not *perfectly* safe.  What if the poor user who includes
square.h does

	# include "square.h"

	...
	# define Tsquare1	foo; bar
	...
	square(i++,&result);

But I agree, it's safe enough to make it worth the remaining risk.
And it would be nice to have C++'s inline facility.
-- 

|| Tom Stockfisch, UCSD Chemistry	tps at chem.ucsd.edu



More information about the Comp.lang.c mailing list