Yes. It is called undefined behaviour. C11 6.7.3p6:
- If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
With undefined behaviour explained as:
undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
NOTE: Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
(emphasis mine)
Compiling without optimization enabled is the same as buying a Ferrari and always driving on the first gear only. What happens if you use gcc
and compile with -O3
?
With -O3
my GCC produces code that is equivalent to
#include <stdio.h>
int main(void) {
printf("%d", 5);
return 0;
}
How about this program then:
#include <stdio.h>
int main(void) {
const char *foo = "Hello world!";
char *bar = (char*)foo;
bar[0] = 'C';
printf("%s\n", foo);
}
Using my GCC and -O3
it crashes. But if you use Clang, it will print Hello world!
... and if you look at the assembly Clang figured out that it can be optimized to
int main(void) {
puts("Hello world!");
}