+ 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++?
6 Respostas
+ 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"...
+ 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.
+ 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....
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