PATCH COMMITTED: Don't break tests for enum in range
Mark Mitchell
mark@codesourcery.com
Wed Jun 6 21:14:00 GMT 2007
Ian Lance Taylor wrote:
> enum E { V = 1 };
> static const E E_MIN = V;
> static const E E_MAX = V;
>
> bool valid(E v) { return v >= E_MIN && v <= E_MAX; }
>
> int main() { return valid(E(2)); }
>
> Here the test in main was returning 1 when one would expect it to
> return 0.
>
> I believe this i technically permitted by the language, as casting a
> value to an enum, where the value is not a member of the enum, is
> unspecified behaviour. But this code seems natural enough and I don't
> think we really want to break it. At least not casually and without
> warnings.
There is a slippery slope here, not that we should necessarily worry
about that... The only reason this code seems natural is that "2" fits
in an "int", and, of course, C says that "E" is an "int" underneath. If
E_MAX is 2^32-1, and 2 is 2^32 (as a long long), then it doesn't seem as
natural.
If we really want this kind of code to work, I think we (a) need to
define the conversion to actually truncate to the maximum number of bits
allowed by the enum, which would pessimize some code, or (b) need to set
the MIN/MAX values to the natural values implied by the full size of the
enum storage.
But, I don't see any good reason to go out of our way to make this code
work. There are ways to write "valid" in a portable conforming way, and
this way isn't one of them. :-)
--
Mark Mitchell
CodeSourcery
mark@codesourcery.com
(650) 331-3385 x713
More information about the Gcc-patches
mailing list