Re: Strange enum type conversion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Hajo,

Normal promotion rules apply.

You have both:
1 << 31 (which is a signed int)
0xFFFFFFFF (which is an unsigned int)

PRESUMING that int is 32-bit, and long is 64-bit...

The use of both of those together makes the enum values signed long int, in
C++.  (Not so in C.)

I strongly recommend you avoid mixing signed int and unsigned int values in
your enum.  Therein lies the path to madness.

For unsigned bias, use:

1U << 31             // explicit unsigned
(unsigned)1 << 31    // explicit unsigned
0xFFFFFFFF           // implicit unsigned
(unsigned)0xFFFFFFFF // explicit unsigned
0xFFFFFFFFU          // explicit unsigned
~0U                  // explicit unsigned

For signed bias, use:
1 << 31              // signed int
(int)0xFFFFFFFF      // explicit cast to signed int
~0                   // signed int

Also be aware that if your "1 << 31" goal is to set the high bit, then your
code is not portable.  If the platform has 64-bit int, you will instead be
setting a middle bit.  If the platform has 16-bit int, such a shift is
undefined behavior.

Consider instead:
1 << (((CHAR_BIT) * sizeof(int)) - 1) // CHAR_BIT from <climits>
~0

HTH,
--Eljay



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux