[R] understanding lexical scope

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Dec 20 16:16:54 CET 2008

Wacek Kusnierczyk wrote:
> Peter Dalgaard wrote:
>> One distinction is if you have things like
>> #define f(x) 2*x
>> #define g(y) f(y+2)
>> (in the C language preprocessor syntax), then you end up with g(y) as
>> y+2*2 (i.e., y+4), whereas the corresponding function calls give
>> 2*(y+2). Also, and the flip side of the original question: Macros have
>> difficulties with encapsulation; with a bit of bad luck, arguments
>> given to f() can modify its internal variables. 
> using c macros, you end up with g(y) substituted by 2*y+2, rather than
> y+2*2, as you say (and rather than 2*(y+2), which you'd effectively get
> using a function).

Oops. Yes. I suppose I had x*2 there at some point....

> that's why you'd typically include all occurences of all macro
> 'parameters' in the macro 'body' in parentheses:
> #define f(x) 2*(x)
> some consider using c macros as not-so-good practice and favour inline
> functions.  but macros are not always bad; in scheme, for example, you
> have a hygienic macro system which let's you use the benefits of macros
> while avoiding some of the risks.
> vQ

    O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907

More information about the R-help mailing list