Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

According to the C standard, may macros with arguments collide with identifiers?

Tags:

c

I think it's better illustrated with an example. With a struct like this:

typedef struct {
    int a;
    char b;
} Foo;

Define a macro:

#define Foo(A, B) (Foo){ A, B }

Which can then be used like this:

Foo foo;
foo = Foo(1, 'c');

I've been using this pattern for a while, and for me it's a very elegant way of initializing structs. It works in GCC and Clang (and TCC I think), but in some lesser-known C compilers (like Plan 9's C compiler) it doesn't.

What does the C standard dictates about that topic?

like image 680
José Miguel Avatar asked Nov 26 '25 13:11

José Miguel


2 Answers

Excerpt from §6.10.3.10 of the C11 standard:

Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition (an invocation of the macro).

So, no, you should not worry. A function-like macro is only replaced if the macro name is followed by an opening parenthesis (.

like image 157
DeiDei Avatar answered Nov 28 '25 03:11

DeiDei


The preprocessor does text substitution, it doesn't know anything about the C language. Thus, it doesn't care about C identifiers.

So, no, a macros cannot collide with an identifier.

like image 34
ForceBru Avatar answered Nov 28 '25 04:11

ForceBru



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!