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.
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!
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.
So the address of a variable cannot be changed as it is constant throughout the lifetime of the variable.
It's also possible that a variable doesn't have an address at all. If declared with the register
keyword, it is not allowed to take the address of such a variable. While the specifics are implementation defined, such a variable could reside entirely in a CPU register in which case it has no address.
If a particular variable never has its address taken, the compiler might also optimize away the variable's address and store it in a register.
Regarding your examples:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With