This code compiles (and appears to work) with both GCC and Clang:
#include <iostream>
struct Foo {
enum { number = 42 };
};
int main()
{
Foo bar;
std::cout << bar.number << std::endl;
}
See it here.
It was surprising to me that the compiler accepts bar.number
; all text books I can find teach to use Foo::number
to access the enumerated value.
Is this code valid? Note that GCC gives a weird warning ("variable 'bar' set but not used"), while Clang doesn't complain about it.
It's perfectly valid:
[C++11: 7.2/10]:
Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier. Each scoped enumerator is declared in the scope of the enumeration. These names obey the scope rules defined for all names in (3.3) and (3.4). [..] An enumerator declared in class scope can be referred to using the class member access operators (::
,.
(dot) and->
(arrow)), see 5.2.5.
The same text (minus rules for scoped enums) can be found in the C++03 standard, at the same location.
I have to admit, this surprises me somewhat as well. I'd have expected ::
to be the only valid mechanism.
The warning you get in GCC is not about the use of the enum, but about the fact that you use nothing but the enum. In such a case, you'd typically write Foo::number
and avoid instantiating a Foo
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With