Reputation: 131517
This code:
enum : unsigned { foo = 4 };
enum : unsigned { bar = 32 };
int main() { return bar > foo; }
gives me the following warning (with GCC 5.4.0):
$ g++ --std=c++11 -o a a.cpp
a.cpp: In function ‘int main()’:
a.cpp:4:27: warning: comparison between ‘enum<anonymous>’ and ‘enum<anonymous>’ [-Wenum-compare]
int main() { return bar > foo; }
^
Why is that? I've specified exactly which types these enum values have, there's nothing indeterminate about comparing them. I've even used the same type for both enums (not that it should matter). So what's the deal here?
Note that clang (3.8.0) doesn't produce this warning, even with -Wall
.
Upvotes: 3
Views: 1209
Reputation: 171263
Why is that? I've specified exactly which types these enum values have, there's nothing indeterminate about comparing them. I've even used the same type for both enums (not that it should matter). So what's the deal here?
The warning doesn't say anything about indeterminate, it tells you that you're comparing distinct types. If the values are represented by different types then it suggests they mean different things, and so comparing them might be questionable. As David said, comparing N apples to M oranges is odd and deserves a warning.
The underlying type doesn't change anything, because foo
is not an unsigned
, and bar
is not an unsigned
. If you wanted to compare unsigned
values then the compiler assumes you'd be using unsigned
and not enumeration types.
From your comment on the other answer:
Because I use enums for constants in (different) classes - things like limits and sizes.
Why? What's wrong with using constexpr static data members for that?
This is covered in the C++ Core Guidelines, see Avoid unnamed enumerations:
Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.
Alternative: Use constexpr values instead.
Upvotes: 2