Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[[maybe_unused]] on enumerator

Looking at the specification of the [[maybe_unused]], it states:

Appears in the declaration of a class, a typedef­, a variable, a non­static data member, a function, an enumeration, or an enumerator. If the compiler issues warnings on unused entities, that warning is suppressed for any entity declared maybe_unused.

As this mentions enumerator, I kinda expect it to have a use-case. As the only thing I could come up with is the -Wswitch warning, I tried it with Clang, GCC and MSVC.

enum A
{
    B,
    C [[maybe_unused]]
};

void f(A a)
{
    switch (a)
    {
        case B: break;
    }
}

All 3 compilers give me a variation of following warning:

<source>:9:13: warning: enumeration value 'C' not handled in switch [-Wswitch]
    switch (a)
            ^

Live code

Is this a valid use case for using this attribute, are there other use cases for adding the attribute at this location or is this just a useless addition?

like image 769
JVApen Avatar asked Jan 28 '18 16:01

JVApen


2 Answers

The intention of this attribute is to declare that an entity might never be made use of, and if that's the case, the implementation shouldn't bother warning you that somewhere, for example, you might be using a wrong entity.

switch statements are a completely different matter altogether: not handling an enumerator is problematic even if the enumerator is never used in that TU; it indicates a logical gap in your program. What if that function has external linkage, and someone else invokes it with that enumerator?

In short, even in TUs in which we marked an enumerator as potentially unused (which feels pointless, because at namespace scope they often are), covering it in your program logic is still very well-advised (and Clang is quite right in giving you that advice).

like image 139
Columbo Avatar answered Oct 16 '22 14:10

Columbo


A bug was logged for Clang and marked as resolved: https://bugs.llvm.org/show_bug.cgi?id=36231

This seems to confirm that the enum value is allowed to be missing in a switch without warning in case it is tagged with [[maybe_unused]]

like image 1
JVApen Avatar answered Oct 16 '22 15:10

JVApen