Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing const value in C

Tags:

c++

c

I find that in the following code snippet

const int i = 2;  
const int* ptr1= &i;  
int* ptr2 = (int*)ptr1;  
*ptr2 =3;

i's value changes to 3. What I could like to know is why is this allowed. What are the situations in which this could become helpful?

like image 961
Manas Avatar asked Sep 14 '10 13:09

Manas


People also ask

Can we change value of const in C?

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.

Can you change the value of a 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.

Can I modify a const pointer?

Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant. A const pointer is a pointer whose address can not be changed after initialization.


2 Answers

It's allowed because you have overruled the constness of ptr1 by casting it to a non-const pointer. This is why casts can be very dangerous.

Note that some compilers, such as GCC, will not allow you to cast away const status like this.

like image 117
Graham Borland Avatar answered Nov 07 '22 00:11

Graham Borland


You have broken the constantness guarantee by playing pointer tricks. This is not guaranteed to work all the time and could invoke almost any behavior depending on the system/OS/compiler that you throw it at.

Don't do that.

Or at least don't do that unless you really know what you are doing and even then understand that it is not in the least portable.

like image 28
dmckee --- ex-moderator kitten Avatar answered Nov 06 '22 22:11

dmckee --- ex-moderator kitten