tech-kern archive

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

Re: introducing flags_t



On whether to introduce a flags_t type:  I don't like flags_t, but I do
like using unsigned types for flags (e.g. unsigned int, uint32_t, etc.).

On whether (flags & FLAGX) is problematic when flags is signed:

On Wed, 22 Apr 2009, David Laight wrote:
> If FLAGX is the msb this might be (1 << 31), (1u << 31), 0x80000000 or
> 0x80000000u I think the compiler might object to the first - but the
> other 3 are all unsigned (on a 32bit arch).

Yes, the compiler may well object to the first.  Assuming int is a
32-bit type, (1 << 31) is formally undefined, per section 6.5.7 of the
C99 standard, because the mathematical value of 1<<31 is positive, but
it is too large to be represented as a positive value in a 32-bit C int.

However, if FLAGX is unsigned (e.g. #define FLAGX (1u<<31), #define
FLAGX 0x80000000, or #define FLAGX 0x80000000u), and flags is signed
with the high bit either set or unset, and the implementation represents
integers using 32-bit two's complement, then (flags & FLAGX) is defined
and does what you would expect.  That may involve a few too many "if"s
for comfort.

> 'int_var & unsigned_var' will implicitly cast the int to unsigned -
> which is (at least for 2s compiliment systems) defined to copy the
> bit-pattern over. So this will DTRT.

Right.  (Well, it's actually defined in terms of repeated addition or
subtraction until the result is in range, but the result on a two's
complement system is equivalent to copying the bit pattern.)

> So the only plausible problem is if the compiler saturates the (1 << 31)
> calculation generating ((1 << 31) - 1). I don't think gcc ever does this!

But some other compiler could, since the result is undefined.

--apb (Alan Barrett)


Home | Main Index | Thread Index | Old Index