C bitfields guarantees
Richard Andrew Cattermole (Rikki)
richard at cattermole.co.nz
Fri Jul 5 05:37:50 UTC 2024
Today many people have spent some time to try and understand
Walter's belief that C is "good enough" for bit fields in terms
of guarantees.
I believe I have understood a core component to this.
From the C23 standard:
> An implementation may allocate any addressable storage unit
> large enough to hold a bit-field. If
enough space remains, a bit-field that immediately follows
another bit-field in a structure shall be
packed into adjacent bits of the same unit. If insufficient space
remains, whether a bit-field that
does not fit is put into the next unit or overlaps adjacent units
is implementation-defined. The
order of allocation of bit-fields within a unit (high-order to
low-order or low-order to high-order) is
implementation-defined. The alignment of the addressable storage
unit is unspecified.
What matters is the _initial_ type in the bit-field, the rest of
the types _do not_ matter.
As long as you _do not_ start and finish in two separate memory
addresses for that initial type it will be predictable.
I have filed a
[ticket](https://github.com/dlang-community/D-Scanner/issues/955)
for dscanner to introduce a warning to tell you that the compiler
is going to do a bad thing, that will cause you problems and the
compiler will not assist you.
Ideally, we wouldn't allow it for ``extern(D)`` code at all.
As of right now, assuming we get Dscanner to give the warning I
can withdraw my concerns, although I do think that ``extern(D)``
shouldn't be offering you such a heavy foot-gun.
More information about the Digitalmars-d
mailing list