Macros with the same name

What happens when I have several #defines with the same name (in one file):

eg:

 #define Dummy 1 #define Dummy 2 

I do NOT intend to use it, but have seen something like this in production code.

+5
source share
3 answers

This is a violation of the restriction, and as such, an appropriate compiler is required to run the diagnostic.

C11, 6.10.3 Macro replacement :

An identifier that is currently defined as an object macro is not overridden by another preprocessing directive #define unless the second definition is an object-like macro definition and the two replacement lists are identical. [..]

As already noted, this is not a violation of the restrictions if the replacement is identical. So

 #define X 1 #define X 2 

diagnostics required; while

 #define X 1 #define X 1 

OK. Similar restrictions apply to function type macros (C11, 6.10.3, 2).

+9
source

It:

 #define Dummy 1 #define Dummy 2 

matches with:

 #define Dummy 2 

But you'll probably get (I'm not sure what the standard says) a warning like 'Dummy': macro redefinition for the second #define

In other words: the last #define wins.

If you want to do something right, you should use #undef :

 #define Dummy 1 #undef Dummy #define Dummy 2 // no warning this time 

By the way: there are scenarios where it is normal to change the definition of a macro.

+4
source

Example from C # 6.10.3.5p8 standards

EXAMPLE 6 To demonstrate redefinition rules, the following sequence is valid .

  #define OBJ_LIKE (1-1) #define OBJ_LIKE /* white space */ (1-1) /* other */ #define FUNC_LIKE(a) ( a ) #define FUNC_LIKE( a )( /* note the white space */ \ a /* other stuff on this line */ ) 

But the following overrides are invalid :

  #define OBJ_LIKE (0) // different token sequence #define OBJ_LIKE (1 - 1) // different white space #define FUNC_LIKE(b) ( a ) // different parameter usage #define FUNC_LIKE(b) ( b ) // different parameter spelling 

[emphasis mine]

Therefore this

 #define Dummy 1 #define Dummy 2 

not valid.

0
source

Source: https://habr.com/ru/post/1276034/


All Articles