macros w/o side effects

Sam Shen laba-3hd at tarantula.berkeley.edu
Tue May 16 07:38:24 AEST 1989


In article <8420 at phoenix.Princeton.EDU> bernsten at phoenix.Princeton.EDU
(Dan Bernstein) writes:

   Since C is not fully expression-based, it is impossible to do the
   above conversion for functions that you're using as functions
   rather than as procedures (i.e., functions that return a type and
   may not take up an entire statement). One can to some extent use
   the comma operator, but since one can't really declare local
   variables without { }, the results can't be nested. However, any
   procedural function can be quite safely converted into a macro.

GNU C allows this.  From the gcc manual:

A compound statement in parentheses may appear inside an expression in GNU
C.  This allows you to declare variables within an expression.  For
example:

({ int y = foo (); int z;
   if (y > 0) z = y;
   else z = - y;
   z; })

is a valid (though slightly more complex than necessary) expression
for the absolute value of foo().

The manual goes on to note that with the typedef extension, we can
do really neat things like:

#define max(a,b) \
  ({typedef _ta = (a), _tb = (b);  \
    _ta _a = (a); _tb _b = (b);    \
    _a > _b ? _a : _b; })

Anyhow Dan Bernstein dreams on...

   What we really want here is a feature often observed to be missing from C:
   inline functions. Inline functions need not be syntactically
   different from normal functions; perhaps we could add an ``inline''
   keyword to a function declaration, with the restriction that the
   function must be defined there (in the header file). A different
   approach would be to make C fully expression-based, so that the
   comma operator would disappear in favor of semicolons; the idea is
   to allow all possible statement constructs as expression
   constructs. Of course, this must include local variables.

   ---Dan Bernstein, bernsten at phoenix.princeton.edu

GNU C has this too.  We could say

inline int max(int a, int b)
{
	return a > b ? a : b;
}

But then we would have the automatic typing of the macro above.

	-Sam Shen
	laba-3hd at web.berkeley.edu
--
----------
Sam Shen				resident of 260 Evans Hall, UCB, 94720.
...!ucbvax!web!laba-3hd		| "Say yur prayers, yuh flea-bitten varmit!"
laba-3hd at web.berkeley.edu	| 		--Yosemite Sam



More information about the Comp.lang.c mailing list