We are studying for our CS midterm on Tuesday.
Our professor put some study material online, including the following:
“Further, you should be able to draw a memory diagram given some code, such as:”
void foo( int &x )
{
x = 1000;
}
void bar( int *x )
{
*x = 1000;
}
void foobar( int x )
{
x = 1000;
}
int main()
{
int x = 1234;
int &y = x;
int *z = &x;
int array_1[5];
int *array_2[5];
array_1[0] = 10;
array_2[0] = (int*)10;
array_2[1] = &y;
array_2[2] = &x;
foo( x );
foo( y );
foo( *z );
bar( &x );
bar( &y );
bar( z );
foobar( x );
foobar( y );
foobar( *z );
return 0;
}
We are trying to go through it one step at a time, to see what is allocated on the stack, what is allocated on the heap, and what is the value of each thing.
What we don’t understand is:
&y holds the address of x, but &y = &x… so what is the address of y? Like, doesn’t the stack need to hold y???
Long story short – there is no
spoony. So nothing will be allocated on stack fory. This is becauseyin your case is a reference.Reference is just an alias and has no address. In other words – it is the same thing as
x, but named differently. That’s how you should think of references as a C++ programmer. In fact, compiler might use an address of the object in order to implement a reference (i.e. when you pass by reference). And even in that case it might be only stored in a register, thus have no memory address. But these are implementation details you are not supposed to know about 🙂 I recommend you check out this C++ References FAQ.