Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const variable in c++

Tags:

c++

these are the some silly question ..i want to ask..please help me to comprehend it

const int i=100;   //1
///some code
long add=(long)&i;  //2

Doubt:for the above code..will compiler first go through the whole code
for deciding whether memory should be allocated or not..or first it ll store the
variable in read only memory place and then..allocate stroage as well at 2

doubt:why taking address of variable enforce compiler to store variable on memory..even
though rom or register too have address

like image 834
user388338 Avatar asked Sep 11 '26 23:09

user388338


1 Answers

In your code example, add contains the address, not the value, of i. I believe you may have thought that i was not stored in normal memory unless/until you take its address. This is not the case.

const does not mean the value is stored in ROM. It is stored in normal memory (often the stack) just like any other variable. const means the compiler will go to some lengths to prevent you from modifying the value.

const is not, and was never intended, to be some sort of security mechanism. If you obtain the address of the memory and want to modify it, you can do so. Of course this is almost always a bad idea, but if you really need to do it, it is possible.

like image 120
Nate Avatar answered Sep 14 '26 12:09

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!