3

Here is a small code in which the conflict occurs. is there any way to get around this correctly?

#define DEBUG 0

enum class TypeEnum : int
{
    DEBUG = 0,
    INFO = 1
};
east1000
  • 1,240
  • 1
  • 10
  • 30
  • 4
    There is also a standard(?) `NDEBUG` that you can use when compiling (meaning, if defined, it's a release build, otherwise it's a debug build). It's checked by standard functions like `assert` and you can use it in your own code too instead of `#define DEBUG 0`. – Ted Lyngmo Aug 31 '21 at 20:49
  • Just before `enum class TypeName` add this: `#undef DEBUG` – Eljay Aug 31 '21 at 22:44

1 Answers1

5

It's the nature of the preprocessor. Lines beginning with # are commands to the preprocessor. #define is a command that defines a text replacement, which will rewrite your code when preprocessed. In this case, all instances of DEBUG will be replaced with 0, so the code becomes:

enum class TypeEnum : int
{
    0 = 0,
    INFO = 1
};

Which, of course, doesn't make sense.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • thank you, I will then choose unique names for the enum class, because define DEBUG is not in my code. – Олег Привалов Aug 31 '21 at 20:47
  • 2
    @ОлегПривалов by convention identifiers with ALL_CAPS are used for preprocessor macros, so just avoid declaring C++ identifiers with all caps. – bolov Aug 31 '21 at 20:50
  • @bolov That's only a convention, though. You can't depend on naming conventions, especially around enums. – Joseph Larson Sep 01 '21 at 14:08
  • @JosephLarsonI am not talking about a convention on enums. I am talking about a convention on macros. Because macros by convention are ALL_CAPS and name conflicts with macros are bad (as you saw) it's a best practice to not use ALL_CAPS for anything except macros. It's true sometimes this macros convention isn't followed (cough MSVC `min`, `max` cough cough) and that can wrecks havoc on code, but that is an exception. Even in those cases, it doesn't hurt to avoid ALL_CAPS for C++ names. – bolov Sep 01 '21 at 20:46
  • @JosephLarson If you are talking about inheriting a code base where enums are defined with ALL_CAPS, then yes, that's a problem and you need to take care of those enums when a conflict appears. – bolov Sep 01 '21 at 20:46
  • @bolov you don't always have a choice of "take care of those enums". You cannot depend on naming conventions. It doesn't matter if it's a convention. It's not enforced by the standard, so you know there are libraries out there that don't follow it. Now, probably macros do because that's been a standard for a long time (K&R days). But enums? Not so much. For instance, I'm looking at the standard PubNub includes (the FIRST place I looked): their enums are all-caps. Is convention a good thing? Yes. Can you depend on it? No. – Joseph Larson Sep 02 '21 at 21:30