James Kuyper
9/1/2011 4:24:00 PM
On 09/01/2011 11:28 AM, skillzero@gmail.com wrote:
> Is there a compliant way of getting the offset of a field within a
> field? I'm mainly using this to do compile-time checks that fields are
> at the offset I expect them. I'm using offsetof( NameOfStruct,
> field1.field2 ) now and this works, but with some compilers, I'm
> getting a warning about "Using extended field designator is an
> extension". Here's an example:
>
> typedef struct
> {
> uint8_t x;
> uint8_t y;
> struct
> {
> uint8_t z;
>
> } fields;
>
> } Test;
>
> compile_time_assert( offsetof( Test, x ) == 0 ); // Works
There's not much point in testing that one: on a conforming
implementation of C, it's guaranteed to be 0.
> compile_time_assert( offsetof( Test, y ) == 1 ); // Works
> compile_time_assert( offsetof( Test, fields.z ) == 2 ); // Works, but
> warns about an extension.
>
> Is there a way to do this in a compliant way?
offsetof(Test,fields) should give you the offset of z, for the same
reason that offsetof(Test,x) should give you a 0.
Of course, that answer wouldn't help if "fields" had multiple members.
The solution is to give "fields" a named type:
struct some_name {
uint8_t z;
double d;
} fields;
Then, instead of testing for offsetof(Test, fields.d), test separately
for offsetof(Test, fields) and offsetof(struct some_name, d).