c - Using macro in C11 anonymous struct definition -



c - Using macro in C11 anonymous struct definition -

the typical c99 way extending stuct like

struct base of operations { int x; /* ... */ }; struct derived { struct base of operations base_part; int y; /* ... */ };

then may cast instance of struct derived * struct base of operations * , access x.

i want access base of operations elements of struct derived * obj; directly, illustration obj->x , obj->y. c11 provide extended structs, explained here can utilize feature anonymous definitions. how write

#define base_body { \ int x; \ } struct base of operations base_body; struct derived { struct base_body; int y; };

then may access base of operations members same it's part of derived without casts or intermediate members. can cast derived pointer base of operations pointer if need do.

is acceptable? there pitfalls?

there pitfalls.

consider:

#define base_body { \ double a; \ short b; \ } struct base of operations base_body; struct derived { struct base_body; short c; };

on implementation sizeof(base) == sizeof(derived), but:

struct base of operations { double a; // padding here short b; } struct derived { double a; short b; short c; };

there no guarantee @ origin of struct memory layout same. hence cannot pass kind of derived * function expecting base *, , expect work.

and if padding not mess layout, there still potential problem trap presenstation:

if 1 time again sizeof(base) == sizeof(derived), c ends area covered padding @ end of base. passing pointer of struct function expects base* , modifies it, might impact padding bits (padding has unspecified value), perchance corrupting c , maybe creating trap presentation.

c macros struct coding-style c11

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -