How does a compiler, C or C++, (for example, gcc) honors the const
declaration?
For example, in the following code, how does the compiler keeps trac
As others have said, const
is tracked by the compiler the same way the compiler tracks the fact that a variable is an int
. In fact, I have read that at least gcc considers const int
a distinct type from int
, so it's not even tracked as a modifier, it's tracked the exact same way as an int
.
Note that you actually can change the value of a const
via pointer casting, but the result is undefined:
#include
#include
int main(void) {
const int c = 0;
printf("%d\n", c);
++*(int*)&c;
printf("%d\n", c);
}
On my machine using gcc, this prints
0
1
But compiling with g++ gives
0
0