Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I define macros with the same name

What happens when I have multiple #defines 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?

like image 470
Kami Kaze Avatar asked Mar 23 '18 10:03

Kami Kaze


People also ask

What is correct way to define macro?

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

Can you define a macro with another macro?

You cannot define macros in other macros, but you can call a macro from your macro, which can get you essentially the same results.

What Cannot be included in a macro name?

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.

Can macro names contain both numbers and letters?

Macro variable names must start with a letter or an underscore and can be followed by letters or digits.


2 Answers

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

like image 142
P.P Avatar answered Sep 20 '22 09:09

P.P


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.

like image 32
Jabberwocky Avatar answered Sep 19 '22 09:09

Jabberwocky