0

I am parsing a complex grammar which requires me to define an enum class like so:

enum class NULLSTYLE {
    NULL,
    NOTNULL
};

Since I could just use 0 or nullptr in C++11, can I somehow suppress or overwrite C++'s own definition of NULL so that I may stay true to my grammar?

Arne Wolframm
  • 367
  • 4
  • 16
  • 1
    As far as I know, `NULL` is a macro, so you probably can `#undef` it in the header right before you use it? Though http://stackoverflow.com/a/9003503/342384 reads that doing so is UB. – iksemyonov Feb 07 '16 at 06:06
  • 1
    I recommend renaming your identifiers, such as `STYLE_NULL` and `STYLE_NOTNULL`. – Thomas Matthews Feb 07 '16 at 06:27
  • @ThomasMatthews that is what you should do if you aren't using strongly typed enums, else it's redundant. I would recommend OP try to attempt to use something like `ISNULL` if possible. –  Feb 07 '16 at 08:02
  • NULL is not a keyword in either C or C++, and if uyou are parsing another 'complex grammar' it presumably isn't either of those languages in the first place. Your question doesn't make sense. – user207421 Feb 07 '16 at 08:57

1 Answers1

6

NULL is not a keyword. C++11's nullptr is. NULL is a macro. If you don't directly or indirectly include any header which defines it, then in theory you can just use it for anything.

However, in practice, this is quite impossible because:

  1. NULL is defined by many standard headers, and headers can (and generally do) indirectly include a lot of other standard headers. You will hardly want to write an enum which prevents its clients from using the standard library.

  2. Using ALL_UPPERCASE for a non-macro identifier is usually considered bad practice anyway (example reference).

  3. You may deal with legacy code which does not use nullptr but still relies on NULL.

You could #undef NULL, but that's generally a horrible hack. You could no longer write any client code which needs both your enum and the NULL macro, not to mention the fact that it would create endless confusion for everyone maintaining your code.

enum class NULLSTYLE {
    NULL,
    NOTNULL
};

This is just a case of bad naming. Make it something like this:

enum class NullStyle {
    Null,
    NotNull
};
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62