sjsam
sjsam

Reputation: 21965

Can C++ references be extended for more than one variable?

If we have the following lines in our code

int a=6, c=1;
int& b=a;

Then what impact will

(int&) b=c

have on the value of c?

Upvotes: 1

Views: 99

Answers (1)

Daniel Daranas
Daniel Daranas

Reputation: 22634

b is already a int& - you declared it as such. So (int&) b is the same as b. Your cast doesn't make any sense. It is the same as b = c; (after adding the semicolon you missed).

C++ references don't move around refering to several variables - they always refer to the variable they were initialized to. So b = c; will have no present or future effect on c.

Actually, though, your code has undefined behaviour, because for some reason you fail to initialize your variable c and then you use its value.

If your first line had been int a = 0, c = 1; so that you avoid undefined behaviour, then the effect of your code would be to assign 1 (the value of c) to a (and, of course, to its alias b).

Upvotes: 3

Related Questions