Quick question about '&'

I'm a bit confused about the ampersand (&) symbol.

Let me start with an example:

int i = 1;
int * x = &i;
int & y = i;

It is to my understanding that x now contains the address to i and "*x = whatever" would modify i's contents.

I am also under the impression that "y = whatever" also modifies i's contents.

Where I get confused is when I see

x = &i;

Is the ampersand in the above statement different from the ampersand used in declaring y? I've been taught that it means "The address of." I'm just a bit confused because I'm seeing what looks like two different uses of ampersand.

One to declare a "reference" and one to get "the address of." Is this right?

EDIT:
changed "int * x = i" to "int * x = &i"
can't forget that ampersand!

Last edited on
Ok. So I verified that '&' means "The address of" so things like

int x = 5;
int * y = &x;

makes sense to me. 'y' contains the address of 'x' and '*y' (Dereferencing) would modify the contents of 'x'.

What seems new to me is the use of '&' in this way:

int x = 5;
int & y = x;

y += 5;

'y' in this case behaves like a pointer without needing to use '*'. On top of that, the address of 'x' and 'y' are the same. I understand how to use it, but I guess I'm just not used to seeing the '&' used for something other than assigning the address of a variable to a pointer...

I guess I'll just go with the flow. Thanks.
You have the right idea.

your first example illustrates the "address of" operator, and you understand it properly.

the second exampe is a reference. It's similar to a pointer but not quite the same thing. You seem to understand it properly as well.

Power to you!
Topic archived. No new replies allowed.