This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Help with bit-field semantics in C and C++
- From: "Joseph S. Myers" <jsm at polyomino dot org dot uk>
- To: Roger Sayle <roger at eyesopen dot com>
- Cc: gcc at gcc dot gnu dot org
- Date: Mon, 23 Aug 2004 23:53:31 +0000 (UTC)
- Subject: Re: Help with bit-field semantics in C and C++
- References: <Pine.LNX.4.44.0408231641070.2070-100000@www.eyesopen.com>
On Mon, 23 Aug 2004, Roger Sayle wrote:
> Could one of GCC's resident C/C++ language lawyers confirm that the
> behaviour of the following code is undefined?
C++ enums are different from C bit-fields.
C bit-field types act just like integer types of the appropriate width,
including conversions, although conversion to such a type will always
within ISO C be implicit as you can't name them for casts. (In GNU C you
could apply typeof to an expression of bit-field type, as derived for
example by arithmetic on bit-fields wider than int, to get a name for such
a type. This should not be considered a feature. It could however be
considered a defect in ISO C that it allows implementation-defined
bit-field types wider than int but doesn't prohibit sizeof on expressions
of such types that are more complicated than just naming a bit-field.)
C++ bit-fields act in expressions as objects of the underlying type, not a
special restricted-width type, although the promotion rules cover the case
of unsigned bit-fields narrowed than int promoting to int. Values must be
truncated appropriately when stored in bit-field objects.
Whereas enums in C are compatible with their underlying type, enums in C++
act something like integer types with the minimum number of bits that can
hold all values of the enumeration. However, the result of conversion to
an enum type of a value outside the range (of that integer type with the
minimum number of bits) is an unspecified value (*not* undefined).
([dcl.enum] paragraph 9: "the resulting enumeration value is
unspecified".)
Being unspecified means that the result may vary at different points in
the program, and at different executions of the same conversion in the
program. Each execution of a conversion does however have to result in
some value (unspecified, unlike undefined, means there are limits on the
implementation's freedom - in this case, that it results in an enumeration
value). I'm not expert enough at interpreting the C++ standard to
determine whether the reference to "the resulting enumeration value"
requires this value to be within the range of the enumeration. It does
not, however, need to be the normal result of converting to an integer
type or bit-field of that width.
--
Joseph S. Myers http://www.srcf.ucam.org/~jsm28/gcc/
jsm@polyomino.org.uk (personal mail)
jsm28@gcc.gnu.org (Bugzilla assignments and CCs)