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

CME Ned Nowotny ned at pebbles.cad.mcc.com
Tue Jun 20 06:02:15 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
=>> (Jeffrey W Percival) writes: 
=>  [if you rely upon .h files for function declarations,
=>   it is easy to later make a function into a macro]
=>> >Is that interpretation unflawed?
=>> If what was once a function is turned into a macro, programs which
=>> passed arguments with side effects to the function may not work
=>> correctly with the macro.  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.  Going the
=>> other direction is probably considered safe, although some programs
=>> may have depended upon the side effects of the macro which is now a
=>> function.  Probably anyone who does so deserves to suffer, though...
=>
=>Oh dear. I should be burned at the stake for some of the macros I write.
=>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!
=>

However, it is not much fun to debug code with something like the following
call to square():

	square( Tsquare1, &Tsquare2 );

Of course, the author would never use Tsquare[12] as variable names in
code that calls square.  However, other users of his header file might.
There are variable name constructions which would be extremely unlikely
to cause problems, but none guaranteed safe.

Ned Nowotny, MCC CAD Program, Box 200195, Austin, TX  78720  Ph: (512) 338-3715
ARPA: ned at mcc.com                   UUCP: ...!cs.utexas.edu!milano!cadillac!ned
-------------------------------------------------------------------------------
"We have ways to make you scream." - Intel advertisement in the June 1989 DDJ.



More information about the Comp.lang.c mailing list