[GD-General] The joy of type aliasing and C
Brought to you by:
vexxed72
From: Brian H. <ho...@py...> - 2003-12-26 18:04:17
|
About a year and a half ago there was a fairly major brouhaha on the algorithms list about this line of code: int x =3D * ( int * ) &somefloat; Now, let's push aside endianess and size issues, the concern was that since there was "type-aliasing" that Something Bad could happen. Something Bad, of course, being a rather ambiguous statement. I'm aware of all the bad things that can happen if you have type-aliasing in conjunction with pointer aliasing, which is related, but that one line above doesn't seem like it should be bad _with a legal C compiler_. The major concern are optimizations that the compiler may make that affect order. For example: somefloat =3D 1.0f; x =3D * ( int * ) &somefloat; In theory, a heavily optimizing C compiler would see that the assignment to somefloat should not affect the assignment to x since they are incompatible types, which may allow it to decide to assign to somefloat _after_ the assignment to x. But that would be illegal. The C specification states that the end of every expression is a sequence point, and thus the assignment to somefloat MUST be flushed before any subsequent statements are executed. So, I can buy that the aliasing thing is a serious concern if there is concern about a C compiler aggressively optimizing and doing it incorrectly, but that doesn't seem to be the argument. Of course, granted, using a union makes more sense and is a bit cleaner, I'm fine with that: union { int i; float somefloat; } u; u.somefloat =3D 1.0f; x =3D u.i; But according to the C standard, the above is undefined ("If the value being stored in an object is accessed from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined."). Anyone have something more authoritative on this issue? Brian |