The compiler uses the type-based aliasing information
to perform optimizations to the generated code. Contravening the type-based
aliasing rule can lead to unexpected behavior, as demonstrated in
the following example:
int *p;
double d = 0.0;
int *faa(double *g); /* cast operator inside the function */
void foo(double f) {
p = faa(&f); /* turning &f into an int ptr */
f += 1.0; /* compiler may discard this statement */
printf("f=%x\n", *p);
}
int *faa(double *g) { return (int*) g; } /* questionable cast; */
/* the function can be in */
/* another translation unit */
int main() {
foo(d);
}
In the above
printf statement,
*p cannot
be dereferenced to a
double under the ANSI aliasing
rule. The compiler determines that the result of
f += 1.0; is
never used subsequently. Thus, the optimizer may discard the statement
from the generated code. If you compile the above example with optimization
enabled, the
printf statement may output
0 (zero).