Can we assign value to reference variable declaration ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can we assign value to reference variable declaration ?

Refer below code link: https://code.sololearn.com/cyoe8S1PMG5y/?ref=app I am not getting why code is not giving compiler error.... we cannot declare ri reference to *pi as *pi is not variable but it's value of that variable... how this is allowed in c++?

25th Jun 2019, 7:02 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
The refrence ri refers to the address of the the temporary object *pi. Its basically a matter of understanting rvalue and lvalue references. The value given to ri from *pi has an address and it will be stored by ri,but because its a temporary object it would be best if you'd use an rvalue reference instead 'int&& ri=*pi" or make it const "const int& ri=*pi"...
25th Jun 2019, 7:40 AM
Mensch
Mensch - avatar
+ 2
Ketan Lalcheta You should study lvalue and rvalue refrences inorder to get a grasp of what your code did better. There's lots of material online.
25th Jun 2019, 8:10 AM
Mensch
Mensch - avatar
+ 1
thanks all for your answers.... got offline help from a guy and below is what I could feel should be better explanation : + nd - are negative operators / and * are negative operators for each others same way sqrt and square are negative to each other... that way & address of and dereferencing * are negative to each other nd used to gather nullify effect... so, *pi can be returned as *(&i) which makes *pi as i with this logic, int &ri = *pi becomes int &ri = i.... this is the common synatx for reference....
27th Jun 2019, 7:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
sorry to say guys but still I am confused... I still count on *pi as value because of pi being pointer nd how value can be assigned to reference r ? I am a bit aware about returning reference from function nd r l value , but *pi is value and cannot assign to ref is what makes me confused
26th Jun 2019, 2:32 AM
Ketan Lalcheta
Ketan Lalcheta - avatar