Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, can a const variable be modified via a pointer?

I wrote some thing similar to this in my code

const int x=1;
int *ptr;
ptr = &x;
*ptr = 2;

Does this work on all compilers? Why doesn't the GCC compiler notice that we are changing a constant variable?

like image 986
Adi Avatar asked Mar 22 '13 17:03

Adi


1 Answers

const actually doesn't mean "constant". Something that's "constant" in C has a value that's determined at compile time; a literal 42 is an example. The const keyword really means read-only. Consider, for example:

const int r = rand();

The value of r is not determined until program execution time, but the const keyword means that you're not permitted to modify r after it's been initialized.

In your code:

const int x=1;
int *ptr;
ptr = &x;
*ptr = 2;

the assignment ptr = &x; is a constraint violation, meaning that a conforming compiler is required to complain about it; you can't legally assign a const int* (pointer to const int) value to a non-const int* object. If the compiler generates an executable (which it needn't do; it could just reject it), then the behavior is not defined by the C standard.

For example, the generated code might actually store the value 2 in x -- but then a later reference to x might yield the value 1, because the compiler knows that x can't have been modified after its initialization. And it knows that because you told it so, by defining x as const. If you lie to the compiler, the consequences can be arbitrarily bad.

Actually, the worst thing that can happen is that the program behaves as you expect it to; that means you have a bug that's very difficult to detect. (But the diagnostic you should have gotten will have been a large clue.)

like image 56
Keith Thompson Avatar answered Oct 25 '22 04:10

Keith Thompson