On Sat, 02 Jun 2012 00:04:18 -0400 Ernie Wright <ern...@comcast.net> wrote: > On 6/1/2012 2:17 PM, Osmo Antero wrote: > > > I have couple of C structures that I want to distinguish between by > > reading the structures' first (type) field. [...] > > > > Q: Can I assume that the "type" field is always first in the > > structures, so I can read it with: NodeType type = *(NodeType*)node; > > Yes. Structure members are stored in the order in which they're > defined, and a pointer to a structure also points to its first member > (suitably cast). This is guaranteed by the C standards. > > > but can I trust it on all *nix plattforms and GCC compilers. > > Anything that's standards-compliant.
Osmo, You are probably also interested in the strict aliasing rule, as well as alignment. If not, you ought to be, as the strict aliasing rule does not permit casting a pointer from one type to a different type and then dereferencing the pointer pointing to that different type, except in certain defined circumstances (one of which is that you can always cast to char* and dereference, and another of which is that you can always cast back to the original type and dereference). This is an alarmingly often overlooked rule. As it happens, your proposed cast is permitted as an exception to the strict aliasing rule (C99 6.5/7, fifth bullet), to allow the poor man's inheritance in C that you seem to be implementing, and which is used for example by GObject. In a different posting on this list, you seemed to indicate you were using C++. If so, you would be better off either using the C++ typeid system with a virtual method, or use templates with partial specialization. The compiler will then do all the work for you in a less error-prone way. Chris _______________________________________________ gtk-app-devel-list mailing list gtk-app-devel-list@gnome.org https://mail.gnome.org/mailman/listinfo/gtk-app-devel-list