C bitfields guarantees

Walter Bright newshound2 at digitalmars.com
Sun Jul 7 04:47:30 UTC 2024


On 7/6/2024 8:50 PM, Steven Schveighoffer wrote:
> Let's take another example:
> 
> ```c
> struct U {
>    unsigned int x;
>    unsigned long long y: 30;
>    unsigned long long z: 34;
> }
> 
> struct U2 {
>    unsigned int x;
>    unsigned long long y: 34;
>    unsigned long long z: 30;
> }
> ```

Simple solution:

```
struct U {
     unsigned int x;
     unsigned int y:30;
     unsigned long long z:34;
}
```

or:

```
struct U2 {
     unsigned int x;
     unsigned int pad;
     unsigned long long y:30;
     unsigned long long z:34;
}
```

depending on which layout is desired. This is simple, predictable, and portable. 
It's not going to be a mystery to anyone reading the code - it's eminently readable.

An anonymous union can be pressed into service, which can be handy if the type 
of `x` is opaque:

```
struct U {
     T x;
     union {
         ulong pad; // for alignment
         struct {
             ulong y: 30;
             ulong z: 34;
         }
     }
}
```

or use align:

```
struct U {
     T x;
   align(8)
     ulong y:30, z:34;
}
```

There are many existing ways to accomplish this. Adding more language features 
to duplicate existing capability needs a very strong case.


More information about the Digitalmars-d mailing list