Why doesn't this code compile, and what can I do to make it compile?
#include <iostream>
using namespace std;
enum class myEnum : unsigned int
{
bar = 3
};
int main() {
// your code goes here
unsigned int v = 2;
switch(v)
{
case 2:
break;
case myEnum::bar:
break;
}
return 0;
}
ideone:
https://ideone.com/jTnVGq
prog.cpp: In function 'int main()':
prog.cpp:18:16: error: could not convert 'bar' from 'myEnum' to 'unsigned int'
case myEnum::bar:
Fails to build in GCC and Clang, works in MSVC 2013.
We can use enums in C for multiple purposes; some of the uses of enums are: To store constant values (e.g., weekdays, months, directions, colors in a rainbow) For using flags in C. While using switch-case statements in C.
Enums allow us to define or declare a collection of related values that can be numbers or strings as a set of named constants. Unlike some of the types available in TypeScript, enums are preprocessed and are not tested at compile time or runtime.
Enum values or Enum instances are public, static, and final in Java. They are a compile-time constant, which means you can not changes values of Enum instances and further assignment will result in a compile-time error. 9.
An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in switch statements.
The whole purpose of the enum class
was so that its members couldn't be compared directly to int
s, ostensibly improving the type safety of C++11 relative to C++03. Remove class
from enum class
and this will compile.
To quote Lord Bjarne:
(An)
enum class
(a scoped enumeration) is anenum
where the enumerators are within scope of the enumeration and no implicit conversions to other types are provided.
You can simply use such a syntax:
enum class Test { foo = 1, bar = 2 };
int main()
{
int k = 1;
switch (static_cast<Test>(k)) {
case Test::foo: /*action here*/ break;
}
}
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