I’m not much of a C programmer, but I was under the assumption that C macros were almost sort of a find and replace feature where the pre-processor takes the macro definition and puts it wherever it sees the macro name.
This is the Dragon Book’s example of dynamic scope rules and how they apply to macros:
#define a (x + 1)
int x = 2;
void b () { int x = 1; printf("%d\n", a); }
void c () { printf("%d\n", a); }
void main () { b(); c(); }
They also discuss how dynamic scope rules apply to the name x within macro a. I was under the assumption that it would basically replace a with (x + 1) and then compile the program and so the scope rules would be exactly the same as if you had written (x + 1) instead of a (which would be static scope rules).
Could anyone clarify this?
Edit: Book referred to is Compilers: Principles, Techniques & Tools Second Edition. The example quoted is from pages 31-32.
Your understanding of the #define behaviour is correct.
What I think the book means when it says “dynamic scoping” is that the name x is resolved based on the environment where the macro is called, not where it is defined. So if you’ve set a global variable x=3 just before your #define, that’s irrelevant to the value of x in the #define – it will just use the value of x wherever you use the macro – if there is some other local variable x in the function where you use the macro, then the local value will be used.
This is in contrast to lexical scoping (which is what is actually used in the C language, and in almost all modern languages), in which a name refers to its local lexical environment. For example, if you replaced the #define in your example by the simple statement
a = x+1, then the value of a in the function would be one more than whatever x happened to be at the point wherea = x+1appears in the code. It wouldn’t matter if some other local variable named x happened to exist at the point where you use the value a. Similarly, if you defined a functionint f() { return x + 1; }, x would refer to the global variable x, not some other local variable named x that happens to exist where f() is called. If this seems blindingly obvious, it’s because, as I said, pretty much all languages use lexical scope (although Perl, for example, also allows dynamic scope using thelocalfunction).See http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping for a bit more of an explanation of the concept.