Muhammad Hewedy
Muhammad Hewedy

Reputation: 30078

misunderstanding of C++ references

What I used to know about c++ references is that:

  1. The reference should be initialized in the declaration statement
  2. The reference cannot be re-defined once defined

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

Answers (6)

HAMMAD ABDUL HAQUE
HAMMAD ABDUL HAQUE

Reputation: 11

It is a constant variable that has to be initialized in declaration statement and cannot be redefined.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258648

Jedi mindtrick:

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

ds27680
ds27680

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

Karl Knechtel
Karl Knechtel

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

Fred Foo
Fred Foo

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

Giovanni Funchal
Giovanni Funchal

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

Related Questions