------- Comment #2 from edwintorok at gmail dot com 2009-04-25 13:49 ------- (In reply to comment #1) > Casting through a union (2) > > describes an invalid way of doing type-punning.
There is also a citation from C99 on that page: "An object shall have its stored value accessed only by an lvalue expression that has one of the following types: * a type compatible with the effective type of the object, * a qualified version of a type compatible with the effective type of the object, * a type that is the signed or unsigned type corresponding to the effective type of the object, * a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object, * an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or * a character type." I'm casting to a union that has both types as members, why doesn't that fit under the 5th case in the above quote? Also there is a warning for foo(), but there is no warning for bar(), but I think they are exactly the same things wrt to violating or not the aliasing rules. > > The only conforming and portable way is > > unsigned bar(char *x) > { > unsigned un; > memcpy (&un, x, sizeof (un)); > return un; > } That may be too slow for me, I'll go with a static inline function that takes a void* instead of a macro that does the cast. > > I have no opinion on the different levels of warnings (I think this case > should be unconditionally). > -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39895