Re: [GD-General] The joy of type aliasing and C
Brought to you by:
vexxed72
From: Brian H. <ho...@py...> - 2003-12-26 20:51:36
|
On Fri, 26 Dec 2003 21:43:52 +0200, Eero Pajarre wrote: > Brian Hook wrote: > > >> 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. >> > I have understood sequence points quite differently... > > > I see them as rules on what I should do, not as promises what the > compiler will do. >From 5.1.2.3.2: "Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects,10) which are changes in the state of the execution environment. Evaluation of an expression may produce side effects. At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place." That seems pretty clear to me, which is the basic fundamental rule as to why the whole aliasing thing has been somewhat puzzling to me. The language seems to state that: f =3D 1.0f; y =3D * ( int * ) &f; The only snafu is Appendix C's list of sequence points, where it says that a "full" expression is a sequence point, but I'm not quite sure if an assignment is considered a full expression (known full expressions are expressions used in a return; selection statement; function calls; and "the expression statement in an expression"). Brian |