c++visual-c++enumslanguage-lawyerdeclaration

MSVC: Why does use of enum without prior declaration compile?


While playing around with C++, I discovered that the following code

enum E* kind;
int main() { }

compiles on MSVC v19.latest. I expected this to fail, as E is not declared yet. GCC and Clang give appropriate error messages

error: use of enum 'E' without previous declaration

and

error: ISO C++ forbids forward references to 'enum' types

respectively.

Why does above code compile on MSVC? Is MSVC not following the standard? Is it UB, a bug or a feature?


Solution

  • Why does above code compile on MSVC?

    Because you're compiling with Microsoft extensions enabled.

    Like many implementations, MSVC sneakily enables them by default.

    Is MSVC not following the standard?

    The C++ standard says that your code isn't valid C++. However, there is nothing stopping an implementation from extending the C++ langauge to give meaning to programs that are not legal C++. That's what MSVC is doing here.

    If you compile with language extensions disabled, MSVC v19.latest will reject it with the error message

    error C3432: 'E': a forward declaration of an unscoped enumeration must have an underlying type