Macro re-entrancy problem

L

Lauri Alanko

I encountered a somewhat exotic macro problem:


#define FOO(x) BAR_##x
#define BAR_z 42
#define BAR_q FOO(z)
#define BAZ(x) BAR_##x

int main(void) {
int a = FOO(z);
int b = BAZ(q);
int c = FOO(q); // line 9
return 0;
}

$ gcc -o t t.c
t.c: In function 'main':
t.c:9: error: 'z' undeclared (first use in this function)
t.c:9: error: (Each undeclared identifier is reported only once
t.c:9: error: for each function it appears in.)

The preprocessor output from gcc -E is:


int main(void) {
int a = 42;
int b = 42;
int c = FOO(z);
return 0;
}


So it seems that a macro invocation cannot trigger the invocation of
the same macro again, even indirectly, even if the expansion would
ultimately terminate. Is this standard behavior, or a bug in gcc?

Thanks,


Lauri
 
B

Ben Bacarisse

Lauri Alanko said:
I encountered a somewhat exotic macro problem:

#define FOO(x) BAR_##x
#define BAR_z 42
#define BAR_q FOO(z)
#define BAZ(x) BAR_##x

int main(void) {
int a = FOO(z);
int b = BAZ(q);
int c = FOO(q); // line 9
return 0;
}

$ gcc -o t t.c
t.c: In function 'main':
t.c:9: error: 'z' undeclared (first use in this function)
t.c:9: error: (Each undeclared identifier is reported only once
t.c:9: error: for each function it appears in.)

The preprocessor output from gcc -E is:

int main(void) {
int a = 42;
int b = 42;
int c = FOO(z);
return 0;
}


So it seems that a macro invocation cannot trigger the invocation of
the same macro again, even indirectly, even if the expansion would
ultimately terminate. Is this standard behavior, or a bug in gcc?

It's standard. For chapter and verse, see 6.10.3.4 paragraph 2 of C99.

The restriction applies to the macro text being expanded. When the
macro expansion involves further "new" text from the source, the
expansion will be made:

#define M0(x) R1 M1
#define M1(x) R2 M0

M0(a)(b)(c)(d)

expands to R1 R2 R1 R2 M0.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Problem with codewars. 5
about macros 4
macro chain 4
offsetof() Macro Attempt 45
correct macro definitions 7
MACRO help 23
macro with the same name in translation unit 5
Macro expansion : Confusion 2

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top