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
};
2
  • 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. Commented Aug 31, 2021 at 20:49
  • Just before enum class TypeName add this: #undef DEBUG Commented Aug 31, 2021 at 22:44

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

thank you, I will then choose unique names for the enum class, because define DEBUG is not in my code.
@ОлегПривалов by convention identifiers with ALL_CAPS are used for preprocessor macros, so just avoid declaring C++ identifiers with all caps.
@bolov That's only a convention, though. You can't depend on naming conventions, especially around enums.
@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.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.