Reputation: 13160
In c, it is not defined by the standard whether enums are signed or unsigned. However, when I try to compare an enum value to the lowest (ie 0) enumeration constant, I get the warning "pointless comparison of unsigned integer with zero." (Compiler is IAR embedded workbench.)
typedef enum
{
BAR,
BAZ
} Foo;
//later...
Foo x = (Foo)some_integral_value;
if (x >= BAR) // <- this gives me the warning
//stuff
I need to check the range of the enum, however, because it is being converted from an integral type. Is there a good way to do this that avoids the warning, which will still work if the compiler decides to change the underlying type?
Upvotes: 2
Views: 712
Reputation: 54242
It sounds like in C, all enums should have type int
, but I'm leaving these suggestions around, since your compiler is either non-standard C, or compiling as C++.
If you have control over the definitions of these enums, you could just make them start at 1:
enum Foo
{
BAR = 1,
BAZ
};
You could also add a single fake negative value to force it to be signed:
enum Foo
{
NEGATIVE_PLACEHOLDER = -1,
BAR,
BAZ,
};
In C++11, you can give your enum an explicit underlying type:
enum Foo : int
{
BAR,
BAZ
};
See this page, specifically the section that says:
enum name : type { enumerator = constexpr , enumerator = constexpr , ... }
...
2) declares an unscoped enumeration type whose underlying type is fixed
It sounds like the type should always be predictable though:
Values of unscoped enumeration type are implicitly-convertible to integral types. If the underlying type is not fixed, the value is convertible first type from the following list able to hold their entire value range:
int
,unsigned int
,long
,unsigned long
,long long
, orunsigned long long
. If the underlying type is fixed, the values can be converted to their promoted underlying type.
So, if your enum fits in an int
, it should always use an int
.
Upvotes: 1
Reputation: 78903
In C this is a false problem.
int
, anyhowNow to your example
enum Foo
{
BAR,
BAZ
};
//later...
Foo x = (Foo)some_integral_value;
This doesn't even compile, because in C Foo
is not defined to be anything, you must use enum Foo
, or provide an appropriate typedef
, something like
typedef enum Foo Foo;
Perhaps you compile C code with a C++ compiler? In any case, provide a complete example that shows your problem.
Upvotes: 2