What happens when I have multiple #define
s with the same name in one sourcefile:
for example:
#define Dummy 1
#define Dummy 2
I do NOT intend to use it, but saw something similar in production code. Is this covered by the standard?
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(;).
You cannot define macros in other macros, but you can call a macro from your macro, which can get you essentially the same results.
Macro names should only consist of alphanumeric characters and underscores, i.e. 'a-z' , 'A-Z' , '0-9' , and '_' , and the first character should not be a digit.
Macro variable names must start with a letter or an underscore and can be followed by letters or digits.
It's constraint violation and as such, a conforming compiler is required to issue a diagnostic.
C11, 6.10.3 Macro replacement states:
An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. [..]
As noted, it's not a constraint violation if the replacement is identical. So
#define X 1
#define X 2
requires a diagnostic; whereas
#define X 1
#define X 1
is OK. Similar constraints apply for function-like macros (C11, 6.10.3, 2).
This:
#define Dummy 1
#define Dummy 2
is the same as:
#define Dummy 2
But you'll get probably (I'm not sure what the standard says) a warning such as 'Dummy': macro redefinition
for the second #define
In other words: the last #define
wins.
If you want to do things properly, you should use #undef
:
#define Dummy 1
#undef Dummy
#define Dummy 2 // no warning this time
BTW: there are scenarios where it is perfectly OK to change the definition of a macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With