Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope rules for C macros

Tags:

c

macros

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.

like image 489
user12345613 Avatar asked Oct 27 '25 19:10

user12345613


1 Answers

Your understanding is correct: find every use of the identifier a and substitute that a with (x + 1). That is exactly what the preprocessor does.

The only "scope" that we can discuss with respect to an object-like macro (like a) is the scope of the macro itself: The scope of a macro is from the line on which it is defined (with a #define directive) until the line on which it is undefined (with a #undef directive) or until the end of the translation unit (the .cpp and all of the headers it includes), if it is never undefined.

like image 179
James McNellis Avatar answered Oct 30 '25 12:10

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!