[R] understanding lexical scope
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sat Dec 20 13:19:11 CET 2008
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).
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
More information about the R-help
mailing list