Is it possible to change the value of const global or extern global variable? via pointer?
you can change the value of const local variable.
See Question&Answers more detail:osIs it possible to change the value of const global or extern global variable? via pointer?
you can change the value of const local variable.
See Question&Answers more detail:osAlthough it may be possible to appear to change the value of a const
object in some C implementations, this appearance may be an illusion, and it is difficult to do in a controlled way because:
const
.const
object into other expressions, so that the initialization of x
in const int a = 10; int x = 2*a;
initializes x
to 20 without referring to a
at all. It can happen that some uses of a
refer to the memory allocated for it and use the changed value, if you manage to change it, while other uses of a
in the same program use the original value in a built-in way. Obviously, this results in a very confusing program.const
objects in different ways.In many C implementations, constant global data is stored in an area of memory that is marked read-only. Attempting to modify it results in an exception that usually terminates your program. It may be possible to ask the operating system to change this protection and then modify memory. However, doing so risks side effects that come from the compiler assuming that constant data will not change.
When you are able to modify an automatic object (such as one defined instead a function body) but not a static object (such as one defined outside any function), it may be because the static object is kept with constant global data, which is marked read-only, but automatic objects are kept on the stack. The stack contains a mixture of different things, and it is not possible on today’s processors to mark small parts of the stack read-only while leaving other parts writeable. Thus, you may have the physical access to modify const
automatic objects. However, you still do not have the license from the C standard to do so; the behavior is undefined, and there may be hidden side effects that will break your program.
On a separate note, const
does not always mean an object is constant. When an object is defined with const
, the C standard does not define the behavior of attempting to modify it. However, it is possible to add const
to a pointer and remove it later. For example, this is legal code:
int a = 3;
const int *b = &a;
int *c = (int *) b;
*c = 4;
This behavior is needed because the C language was originally designed without const
, so its semantics are not designed to accommodate it, and there are some circumstances where things would not work correctly if const
were always enforced.