I was deubugging a project written in C++ through GDB and discovered that a const was being modified without warning or error by the GNU C++ compiler.
This isn't the program I was debugging, but this is an example of the behavior I witnessed:
#include <iostream>
int main(int argc, char *argv[]) {
const int x = 10;
int *px = (int *)&x;
++*px;
std::cout << "*px: " << *px << "\n";
std::cout << "x: " << x << "\n";
for (int i = 0; i < x; ++i)
std::cout << i+1 << "\n";
return 0;
}
I can't speak for other compilers because I only tested this with GNU C++ compiler, version 4.9.2. Why is something like this allowed? This breaks the entire point of const
objects.
I compiled the above code with g++ main.c -Wall -Werror
The output:
*px: 11
x: 10
1
2
3
4
5
6
7
8
9
10