https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90404
Bug ID: 90404 Summary: No warning on attempts to modify a const Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: david at westcontrol dot com Target Milestone: --- The compiler knows that you can't change an object declared "const", even via a pointer cast. And it (rightfully and helpfully) uses that knowledge for optimisation. But it should also be able to warn about it. const int c = 20; int foo(void) { *((int*) &c) = 10; return c; } Current gcc, with -O2, compiles this to: foo: mov DWORD PTR c[rip], 10 mov eax, 20 ret The write to c is unnecessary, but could trigger a helpful fault message on many target systems (and who cares about the efficiency of incorrect code?). And the compiler correctly optimises the return value to 20 as it knows the write to "c" cannot succeed. However, there is no warning or error message here - even with -Wall -Wextra. With -Wcast-qual, you get a warning - but that will have false positives in cases like : int v = 20; int foo2(void) { const int* p = &v; *((int*) p) = 10; return v; } foo2: mov DWORD PTR v[rip], 10 mov eax, 10 ret The optimiser can see the difference here - I would like warnings to show the difference too.