second draft: add Bitfields to D

Timon Gehr timon.gehr at gmx.ch
Sat May 4 17:21:21 UTC 2024


On 5/4/24 19:05, Timon Gehr wrote:
> On 5/4/24 04:07, Walter Bright wrote:
>>>>
>>> No, this is not correct. It implements it as a field with accessors 
>>> for different groups of bits. The only reason why `union` appears in 
>>> that file is to support bitfields inside a union. This again 
>>> highlights that those are not the same thing.
>>
>> They are the same thing, it is not substantive what label is painted 
>> on it. Anonymous unions can lay fields on top of each other without 
>> explicitly labeling it as a union.
> 
> This is explicitly called a `union`, so I really do not see what you are 
> trying to say.
> 
> Bitfields do not imply union, but they can be in a union, e.g.:
> 
> ```C++
> #include <bits/stdc++.h>
> using namespace std;
> 
> struct S{
>      union{
>          struct {
>              unsigned int x:1;
>              unsigned int y:1;
>          };
>          unsigned int z:2;
>      };
> };
> 
> int main(){
>      S s;
>      s.z=3;
>      cout<<s.x<<" "<<s.y<<endl; // 1 1
>      s.x=0;
>      cout<<s.y<<" "<<s.z<<endl; // 1 2
>      s.y=0;
>      s.x=1;
>      cout<<s.z<<endl; // 1
> }
> ```
> 
> Clearly bitfields are a new and distinct way fields can share the same 
> `.offsetof` in D. Before bitfields, such fields would overlap given they 
> both were of a type with a positive size. With bitfields there is no 
> such overlap.
> 
> BTW: what about `sizeof`? I think in C++ this is disallowed on a bitfield.

Another example:

```C++
#include <bits/stdc++.h>
using namespace std;

struct S{
     union{
         unsigned int x:1;
         unsigned int y:1;
     };
};

int main(){
     S s;
     cout<<s.x<<" "<<s.y<<endl; // 0 0
     s.x=1;
     cout<<s.x<<" "<<s.y<<endl; // 1 1
}
```





More information about the dip.development mailing list