Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we change the value of an object defined with const through pointers?

#include <stdio.h> int main() {     const int a = 12;     int *p;     p = &a;     *p = 70; } 

Will it work?

like image 558
Shweta Avatar asked Sep 27 '10 06:09

Shweta


People also ask

Can we change the value of const using pointer?

Changing Value of a const variable through pointerBy assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier.

Can we change the value const pointer in C?

A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.

Can we change the value of const?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

Can you modify a const array in C?

You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable.


1 Answers

It's "undefined behavior," meaning that based on the standard you can't predict what will happen when you try this. It may do different things depending on the particular machine, compiler, and state of the program.

In this case, what will most often happen is that the answer will be "yes." A variable, const or not, is just a location in memory, and you can break the rules of constness and simply overwrite it. (Of course this will cause a severe bug if some other part of the program is depending on its const data being constant!)

However in some cases -- most typically for const static data -- the compiler may put such variables in a read-only region of memory. MSVC, for example, usually puts const static ints in .text segment of the executable, which means that the operating system will throw a protection fault if you try to write to it, and the program will crash.

In some other combination of compiler and machine, something entirely different may happen. The one thing you can predict for sure is that this pattern will annoy whoever has to read your code.

like image 95
Crashworks Avatar answered Oct 11 '22 13:10

Crashworks