With Clang, the following :
#include <stdio.h>
int main(void)
{ double const x = 1.234;
double *p = (double *) &x;
/* Same with double *p = &x; but with a mere warning from clang
Clang++ does raise an error in this case.
*/
*p = 5.678;
printf("*p = %f\n", *p);
printf(" x = %f\n", x);
if (&x == p) {
printf("&x = %p\n", &x);
printf(" p = %p\n", p);
}
return 0;
}
gives the output:
*p = 5.678000
x = 1.234000
&x = 00000080288FFEA8
p = 00000080288FFEA8
How exactly does the compiler do this? How can the compiler successfully compile and avoid, say, the following output:
*p = 5.678000
x = 5.678000
&x = 00000080288FFEA8
p = 00000080288FFEA8
The behaviour on modifying an object which was originally const
via a cast which removes that const
is undefined.
Whether or not a compiler warns you about undefined behavior is up to the compiler. To do so in full generality is impossible.
Optimising compilers will make assumptions based on the fact that your program does not contain undefined behaviour. The Clang output is consistent with it substituting 1.234
for x
in that printf
call; that's legitimate since x
is not allowed to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With