Abdus Khazi
Abdus Khazi

Reputation: 483

What happens when you redefine a macro?

#define MY_MACRO 3 --> in A.h
#define MY_MACRO 45 --> B.h

//In C.cpp

#include "A.h"
#include "B.h"

..
..
..
int my_value = MY_MACRO;

What will my_value be 3 or 45?

Upvotes: 2

Views: 1083

Answers (2)

eerorika
eerorika

Reputation: 238461

From the standard (draft) [cpp.replace] §2:

An identifier currently defined as an object-like macro (see below) 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. [...]


What happens when you redefine a macro?

When the new definition is different, your program is ill-formed. The compiler is required to show you a diagnostic message (a warning, or an error). The behaviour of an ill-formed program is not defined by the standard. The compiler is free to refuse compiling the program.

What will my_value be 3 or 45?

Whatever your pre-processor/compiler chooses. Or the compiler could refuse to compile it.


Technically, the program would become well-formed if you first undefined the macro. Then the defined value would obviously be the newly defined. However, I do not recommend this, because you can then easily break other rules depending on the order of inclusion of headers in multiple translation units.

Most likely, the two macros are supposed to be separate entities, and there are different files that expect the definition from one header, and not the other. The correct solution is to give each a unique name by renaming one, and change the dependant files to use the new name. Figuring out which files use which definition is may be a challenge. While you're at it, you may want to replace the macro with a constexpr variable.

Upvotes: 6

chex
chex

Reputation: 249

I thought

What happens when you redefine a macro?

It gives redefinition warning for macro.

Still

if you avoid warning and try to run your program

then all we know that in cpp all statements are executed sequentially from the top to the bottom, so whatever the last definition of macro is printed.

What will my_value be 3 or 45?

in your code 45 will be taken as macro definition.

Upvotes: 1

Related Questions