why is it wrong to return by value and store it in reference?
example–in the below program:
int * func(int x){
int y=0;
int *z=&y;
return z;
}
int main(){
int *&z=func(5);
cout<<z<<endl;
return 0;
}
it gives an error:
invalid initialisation of non-const reference of type ‘int &’ from an rvalue of…
what is the meaning of this error and why it occurs?
Return by value and store by reference issue
Hi @Rj.25 ,
func(int x) return int*.
but in dis ->int &z=func(5);
u r trying to store value of int in int &.thats why u were getting an error.
int& means u want to store the value not the address.
so to avoid getting error, use
int *z=func(5); cout<<*z<<endl;
here int *z store by reference and *z outputs the value at that address.
Hope dis help.
If u feel like something is unclear, u can post ur doubts here.
what is the meaning of the line int& means u want to store the value not the address.will the program work fine when the return type is int and we are storing the value in int& in contrast to storing the address in the given function?
@Rj.25,
if u change the return type of function to int, u will have to store the value returned by the function in int only.
int * stores address.
eg. int* j=&n;
so to print value of n, u will write cout<<j;
u cant store int data type in int.
so if return type of function is int, then u should use int only to accept functions value.
eg if int f(x);
then int z=f(x) works but int *z=f(x) gives error.
Hope dis helps.