Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we assign a integer value to a reference variable?

Tags:

c++

It is not possible to assign an integer value to a reference variable directly, say like:

int &x=10; //not possible

Is there any other way we can modify this statement to make it possible?

But not like this:

int a=10;int &x=a;

This works fine. But I want some other way or modify a little bit my expression and make it work!

like image 599
srinuvenu Avatar asked Jul 15 '11 08:07

srinuvenu


3 Answers

The reference as the name says has to reference to something. How do you want to assign a value to it if it doesn't reference anything?

like image 96
Karoly Horvath Avatar answered Sep 30 '22 20:09

Karoly Horvath


The reason it doesn't work is because 10 is of the type "const int". You can turn that into a reference, but you can't make it non-const without violating some logic at the least.

const int &a = 10;

that'll work.

int &b = const_cast<int &>(static_cast<const int &>(10));

will also compile, but you can't modify b (as that would imply modifying the actual "10" value).

like image 27
dascandy Avatar answered Sep 30 '22 19:09

dascandy


The crux is that 10 is a constant – somewhat obviously: you cannot change its value. But if you try to assign it to an int reference, this would mean that the value were modifiable: an int& is a modifiable value.

To make your statement work, you can use a const reference:

int const& x = 10;

But as “cnicutar” has mentioned in a comment, this is pretty useless; just assign the 10 to a plain int.

like image 28
Konrad Rudolph Avatar answered Sep 30 '22 19:09

Konrad Rudolph