Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does each variable in C/C++ point to a constant address in memory?

Tags:

c++

c

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.

  1. 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.

  1. Can someone change the address myBox references too? (Again, I am not referring to pointers *, just normal variables).

  2. Does a normal variable hold a constant address in memory for the life of the program?

Thank you guys for your time and understanding!

like image 847
Walter M Avatar asked Sep 17 '25 10:09

Walter M


1 Answers

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.

like image 73
dbush Avatar answered Sep 20 '25 01:09

dbush