Extending a struct in C -


i came across colleague's code looked this:

typedef struct {   int x; }a;  typedef struct b {   a;   int d; }b;  void fn(){   b *b;   ((a*)b)->x = 10; } 

his explanation since struct a first member of struct b, b->x same b->a.x , provides better readability.
makes sense, considered practice? , work across platforms? runs fine on gcc.

yes, work cross-platform, doesn't necessarily make idea.

as per iso c standard (all citations below c11), 6.7.2.1 structure , union specifiers /15, there not allowed padding before first element of structure

in addition, 6.2.7 compatible type , composite type states that:

two types have compatible type if types same

and undisputed a , a-within-b types identical.

this means memory accesses a fields same in both a , b types, more sensible b->a.x should using if have concerns maintainability in future.

and, though have worry strict type aliasing, don't believe applies here. is illegal alias pointers standard has specific exceptions.

6.5 expressions /7 states of exceptions, footnote:

the intent of list specify circumstances in object may or may not aliased.

the exceptions listed are:

  • a type compatible effective type of object;
  • some other exceptions need not concern here; and
  • an aggregate or union type includes 1 of aforementioned types among members (including, recursively, member of subaggregate or contained union).

that, combined struct padding rules mentioned above, including phrase:

a pointer structure object, suitably converted, points initial member

seems indicate example allowed for. core point have remember here type of expression ((a*)b) a*, not b*. makes variables compatible purposes of unrestricted aliasing.

that's reading of relevant portions of standard, i've been wrong before (a), doubt in case.

so, if have genuine need this, work okay i'd documenting constraints in code very close structures not bitten in future.


(a) wife tell you, , without prompting :-)


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -