C bitfields guarantees
Steven Schveighoffer
schveiguy at gmail.com
Sun Jul 7 15:49:18 UTC 2024
On Sunday, 7 July 2024 at 04:47:30 UTC, Walter Bright wrote:
> 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.
Simple, no. Predictable, yes (it's unambiguous). And not obvious.
What I want is for the compiler to *require* you to do this to
avoid inconsistencies. It is going to be a mystery to anyone
reading it *why* they put these things in there. (hey, I
simplified your code by getting rid of the pad, it comes out the
same anyway due to [my wholly understandable but mistaken
understanding of] alignment!)
To give some examples, we require empty if statements to use {}
and not ;. It doesn't require any new syntax but it helps you
avoid issues that many people make, even though it is allowed in
C.
We require explicit conversion when narrowing the range of an
integer (i.e. assigning a long to an int). This avoids issues
that many people would make, even though it is allowed in C.
> There are many existing ways to accomplish this. Adding more
> language features to duplicate existing capability needs a very
> strong case.
I'm not asking for any new features.
-Steve
More information about the Digitalmars-d
mailing list