I have 3 Questions:
In C/C , variables basically hold an address that points to a memory location where the value is held.
For example:
int myVar = 5;
Here, myVar contains the address that points to a memory location that contains 5. If I change the variable value:
myVar = 10;
The memory address stays the same, but the value is overwritten.
- Is it possible to change what address myVar holds? (I am not referring to pointers *, just normal variables)
How about for object variables:
class Box {. . .}
Box myBox;
In the above example, myBox variable basically holds the address to a location in memory that contains the object.
Can someone change the address myBox references too? (Again, I am not referring to pointers *, just normal variables).
Does a normal variable hold a constant address in memory for the life of the program?
Thank you guys for your time and understanding!
CodePudding user response:
Memory address of a variable - if address exists - is always the same (and thus can't be changed), i.e., in your example, &myVar
is the same within scope. That said, if the function reenters / recurses, then you might have another myVar
that has a different address.
Also note, in practice you likely have some virtual memory management under the ABI that's managed by the OS. So, even if the logical address is the same, the physical address might be remapped. A practical use of this is seen in c -based languages that do garbage collection.
CodePudding user response:
In C/C , variables basically hold an address that points to a memory location where the value is held.
That is not correct. Variables are objects which have an address which does not change during the variable's lifetime and hold a value.
For C, this is described in section 6.2.4p2 of the C standard:
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address and retains its last-stored value throughout its lifetime.
int myVar = 5;
Here, the variable myVar
has some address, i.e. &myVar
, and holds the value 5.
myVar = 10;
This changes the value of myVar
to 10.