Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro redefinition in C and C++

Tags:

c++

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).

like image 542
FrozenHeart Avatar asked Nov 14 '12 17:11

FrozenHeart


People also ask

Can macros be redefined in C?

Once you've defined a macro, you can't redefine it to a different value without first removing the original definition. However, you can redefine the macro with exactly the same definition. Thus, the same definition may appear more than once in a program. The #undef directive removes the definition of a macro.

What is macro in C?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).

How are macros undefined in C?

In the following example, the #undef directive removes definitions of a symbolic constant and a macro. Note that only the identifier of the macro is given. Macros can be undefined from the command line using the /U option, followed by the macro names to be undefined.

What is macro substitution in C?

Macro substitution is a mechanism that provides a string substitution. It can be achieved through "#deifne". It is used to replace the first part with the second part of the macro definition, before the execution of the program. The first object may be a function type or an object.


1 Answers

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.

like image 61
Jerry Coffin Avatar answered Oct 19 '22 11:10

Jerry Coffin