Daniel Berlin wrote:
> It will load the value from memory, true, but who says that the
store to
> memory will happen before that? The compiler is allowed to reorder
the
> statements since it "knows" that foo and *arg cannot alias.
>
If the compiler is smart enough to know how to reorder the statements,
then it should be smart enough to know that reordering will still leave
foo uninitialized, which is obviously an error.
It's also undefined, so we can *and will* reorder things involving
uninitialized variables.
Any time an
optimization/reordering visibly changes the results, that reordering is
broken.
Not in this case.
Hm. If you're going to reorder these things, then I would expect either
an error or a warning at that point, because you really do know that a
reference to an uninitialized variable is happening.
also Note that gcc *guarantees* the union trick will work, even though
the standard does not.
That's good to know, thanks. But frankly that's braindead to require
someone to add all these new union declarations all over their code,
when a simple cast used to suffice, and ultimately the generated code is
the same. And since we have to write code for compilers other than just
gcc, we can't even really rely on the union trick. In this respect, the
standard is broken.
This example is worse, it gives no warning and gives the wrong result
with -O3 -Wstrict-aliasing :
####
#include <stdio.h>
main() {
int i = 0x123456;
int *p = &i;
*(short *)p = 2;
printf("%x\n", i);
}
####
In this case, it's not two different pointers pointing to the same
memory, it's the same pointer. The compiler doesn't even have to guess
whether two different pointers access the same memory - it knows it's
the same pointer, and therefore must be accessing the same memory. I can
understand strange results occurring when there's ambiguity, but there
is no ambiguity here.
--
-- Howard Chu
Chief Architect, Symas Corp. http://www.symas.com
Director, Highland Sun http://highlandsun.com/hyc
OpenLDAP Core Team http://www.openldap.org/project/