nSv23
nSv23

Reputation: 439

Address of operator in c++

When I do the following:

1. int y = 5;
2. int &a = y;
3. cout << &a << endl; // the address of a is the same address of y
4. cout << a << endl;  // this has the value of y, which is 5.
  1. Why does the a has the same address of y? I know that changing a will change y also.
  2. But how do you read line 2? Do you read it as address of a contains the value of y?
  3. Does this mean that a and y share the same physically memory location? Or are there 2 different memory locations with the same address?

Upvotes: 0

Views: 2021

Answers (3)

Akshay Patel
Akshay Patel

Reputation: 85

Read this: http://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htm

  1. int &a = y;

Here in line 2, you are declaring that "Address of 'a' is equal to the address of variable 'y' ".In other words, 'y' has another name 'a'.

  1. cout << &a << endl; // the address of a is the same address of y

I think there cannot be two memory locations with same address. It's just that two variables refer to the same address.

Upvotes: 0

Kaitain
Kaitain

Reputation: 960

References are (broadly) just syntactic sugar for pointers, so a is really just a pointer to y wrapped up with automatic dereferencing. (There is slightly more to it than that, but for the sake of discussion we can think of it that way without getting misled about anything.) So when you ask for the address of a, you are really asking for the underlying pointer value, which has been set to be &y.

When you ask for the value of a, it automatically dereferences the pointer, so it is giving you the value which is at &y. Naturally, this value has y's value.

Does this mean that a and y share the same physically memory location?

No, there are two different memory locations. One holds an int value, the other holds a pointer to that int value.

Or are there 2 different memory locations with the same address?

Pretty much, yes. y is not holding a pointer/address value, though; it is actually holding the integer value itself. (Remember that y is stack memory, not a pointer to a heap object.)

When you take the address of a reference, you are not getting back "a pointer to that reference". You will simply get back the address of the referent itself.

Upvotes: 1

merlin2011
merlin2011

Reputation: 75579

In line 2, you are creating a C++ reference, not using the address of operator. The reference causes a to be roughly equivalent to y for all uses including taking its address.

Effectively the symbol a is just another name for y.

Upvotes: 6

Related Questions