| |
| Posted by Walter Bright in reply to Timon Gehr | PermalinkReply |
|
Walter Bright
Posted in reply to Timon Gehr
| On 5/6/2024 1:37 PM, Timon Gehr wrote:
> On 5/6/24 09:14, Walter Bright wrote:
>> On 5/5/2024 2:08 AM, Timon Gehr wrote:
>>> GCC 11.4.0, clang 14.0.0:
>>>
>>> ```c
>>> #include <stdio.h>
>>> struct __attribute__((packed)) S{
>>> long long x:8;
>>> };
>>> int main(){
>>> printf("%ld\n",sizeof(long long)); // 8
>>> printf("%ld\n",sizeof(struct S)); // 1
>>> }
>>> ```
>>
>> The sizeof there, in both cases, is giving the size in bytes of the memory object the field is a subset of.
>> ...
>
> This is C and neither sizeof is on a memory object, they are both on types. sizeof on x gives a compile error. However, with the DIP, given that you implement packed bitfields in DMD, when importing an example like this one, `x.sizeof` would be eight times as big as the size of the `struct` it is a part of.
Since the memory object that x is in is 1 byte, the sizeof would be 1 byte (if I implemented the packed logic).
> Well, the DIP now says `bitfield.sizeof` is `typeof(bitfield).sizeof`.
Yes, as I didn't know about the packed thing then.
> Well, that will help, but the point was the C standard does not give the guarantees you assumed to hold earlier, and in practice it in fact does not hold, as in this example.
The C standard says nothing about __attribte__((packed), and C doesn't allow sizeof on bit fields, so we can make .sizeof work as we like. The most practical thing is to make it mean the size of the memory object the bitfield is a subset of. Unless (unimplemented) packed bitfields are used, the sizeof is the size of the type.
|