Reputation: 30078
What I used to know about c++ references is that:
The following piece of code perfectly run on g++ 4.6.1
, although it breaks #2:
int a = 10, b = 30;
int& x = a;
x = b;
Upvotes: 3
Views: 162
Reputation: 11
It is a constant variable that has to be initialized in declaration statement and cannot be redefined.
Upvotes: 1
Reputation: 258648
What helped me better understand references is to think of them as names for your variables. int& x = a
just means that when you say x
, you actually mean a
.
Think of references as an alias.
This is pretty clear:
int a = 10, b = 30;
Think of this not as x = 10
, but as "x is a different name for a".
int& x = a;
So now, x
will still reference a
, so you give a the value of b
(30).
x = b;
At this point, x
is still bound to a
, you just changed its value.
So, x == 30
and a == 30
at this point, but if you do:
a = 10;
x
will also equal 10
.
Upvotes: 5
Reputation: 1993
The code from the question does not break 2
at the point you write:
int& x = a;
x becomes an alias for a.
Later you write:
x = b;
That assigns the value of b to a through its alias named x.
Upvotes: 2
Reputation: 61643
The reference cannot be reseated, i.e. caused to refer to a different variable.
It is perfectly possible to modify the variable through the reference.
The basic effect of the reference is that it becomes another name for the value it refers to.
Upvotes: 3
Reputation: 363817
The third statement does not do what you think it does. It assigns the value of b
to x
, and thereby to a
.
Upvotes: 0
Reputation: 9200
You are not redefining the reference, but rather assigning a value to the refered memory location. Do a printf of a
and you'll see it will print 30
instead of 10
;-)
Upvotes: 7