FrozenHeart
FrozenHeart

Reputation: 20746

Macro redefinition in C and C++

I know that this code is valid both in C and C++:

#define FOO 0
#define FOO 0

ISO/IEC 14882:2011

16.3 Macro replacement [cpp.replace]

2 An identifier currently defined as an object-like macro may be redefined by another #define preprocessing directive provided that the second definition is an object-like macro definition and the two replacement lists are identical, otherwise the program is ill-formed. Likewise, an identifier currently defined as a function-like macro may be redefined by another #define preprocessing directive provided that the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical, otherwise the program is ill-formed.

But what about this code?

#define FOO 0
#define FOO FOO

Replacement lists are not identical at the start of preprocessing (only when the first replacement occurs).

Upvotes: 5

Views: 1409

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490108

This is not allowed in either C or C++. The replacement list must be identical. What you're talking about (after the first pass) is the result of processing the replacement list1, not the replacement list itself. Since the replacement list itself is not identical, the code is not allowed.


1 Or at least what the result would be if the preprocessor worked a particular way that happens to be different from how it actually does.

Upvotes: 6

Related Questions