I am not totally sure about C, but C++ allows unnamed bit-fields of 0 length. For example:
struct X
{
int : 0;
};
- Question one: What practical uses of this can you think of?
- Question two: What real-world practical uses (if any) are you aware of?
Edited the example after ice-crime's answer
Edit: OK, thanks to the current answers I now know the theoretical purpose. But the questions are about practical uses so they still hold :)
The C11 standard now allows the inclusion of zero length bitfields. Here is an example from the C Committee draft (N1570), which I believe illustrates a practical usage.
So including the zero length bitfield in between the bitfields
c
andd
allows the concurrent modification ofb
andd
as well.The standard (9.6/2) only allows 0 length bit-fields as a special case :
The only use is described in this quote, although I've never encountered it in practical code yet.
For the record, I just tried the following code under VS 2010 :
The output on my machine is indeed :
4 - 8
.is undefined behavior in C.
See (emphasis mine):
(C11 has the same wording.)
You can use an unnamed bit-field with
0
width but not if there is no other named member in the structure.For example:
By the way for the second declaration,
gcc
issues a diagnostic (not required by the C Standard) with-pedantic
.On the other hand:
is defined in GNU C. It is used for example by the Linux kernel (
include/linux/bug.h
) to force a compilation error using the following macro if the condition is true:You use a zero-length bitfield as a hacky way to get your compiler to lay out a structure to match some external requirement, be it another compiler's or architecture's notion of the layout (cross-platform data structures, such as in a binary file format) or a bit-level standard's requirements (network packets or instruction opcodes).
A real-world example is when NeXT ported the xnu kernel from the Motorola 68000 (m68k) architecture to the i386 architecture. NeXT had a working m68k version of their kernel. When they ported it to i386, they found that the i386's alignment requirements differed from the m68k's in such a way that an m68k machine and an i386 machine did not agree on the layout of the NeXT vendor-specific BOOTP structure. In order to make the i386 structure layout agree with the m68k, they added an unnamed bitfield of length zero to force the
NV1
structure/nv_U
union to be 16-bit aligned.Here are the relevant parts from the Mac OS X 10.6.5 xnu source code:
This is from MSDN and not marked as Microsoft Specific, so I guess this is common C++ standard:
An unnamed bit field of width 0 forces alignment of the next bit field to the next type boundary, where type is the type of the member.