I don't understand how we can modify the value of a const
variable by a pointer. Isn't it undefined behavior?
Yes, it is undefined behavior:
Quote from C18, 6.7.3/7:
"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."
But just because the behavior is undefined, it does not mean you potentially can not do that. As far as I can think of, it is indeed the case, that the compiler will, most of the times your program contains any kind of undefined behavior, not warn you - which is a big problem.
Fortunately in this case, when compiling f.e.:
#include <stdio.h>
int main(){
const int a = 25;
int *p = &a;
*p = 26;
printf("a = %d",a);
}
the compiler will throw a warning:
initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] (gcc)
or
warning: initializing 'int *' with an expression of type 'const int *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] (clang)
but despite that the code contains parts which cause undefined behavior and you can never be sure what it will print on any execution, you get that malicious program compiled (without -Werror
option of course).
Can we modify the value of a const
variable?
So, yes - unfortunately. One can actually modify a const
object, but you never ever should do that, neither intentionally nor by accident.
The method to using register
keyword might be efficient because the address of a register
marked variable can´t have its address taken - means you cannot assign a pointer with the address of the relative variable nor pass it to a function as argument of the respective pointer type.
int * q = (int*)i; *q = 42;
. – Ulloa