1

I'm trying to make my code more readable, So I defined the following macros to shorten access to components within a nested structure.

#define  _ENTRY(i)         policy_data->entries[i]                
#define  _ENTRY(i,j)       policy_data->entries[i].sub_entry[j] 

For attempting this, I get a compiler warning about "_ENTRY" being redefined.

I thought a macro is just a sophisticated way to replace strings defined by some template within a C file. A job which is done by the pre-processor before compilation.

So why does the compiler care about this? How can I achieve the same functionality without an error?

manish ma
  • 1,706
  • 1
  • 14
  • 19
  • 1
    You can't overload macros like that, see here on how to do something similar: https://stackoverflow.com/a/11763277/10411602 – Blaze Mar 14 '19 at 11:10
  • If you care about "why does the compiler care..." see 6.10.3, paragraph 2 –  Mar 14 '19 at 11:11

1 Answers1

3

Using an identifier like _ENTRY itself is a cause for undefined behavior.

The C11 standard states this with respect to identifiers:

7.1.3 Reserved identifiers

1 Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
...
3 If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

So there is the possibility that the entire macro can be removed in certain implementations. This further leads to portability issues as well.

The C11 standard states in the Annexure on Portability and Undefined behavior:

The program removes the definition of a macro whose name begins with an underscore and either an uppercase letter or another underscore

P.W
  • 26,289
  • 6
  • 39
  • 76