I don't seem to get this, when I return a reference from a function, it does the job (also why?), but when I try to return the original variable (the one which the reference was created for), it throws an obvious warning.
Code:
int& ref(int q){
int a = q;
int &r = a;
return r;
}
main(){
int i=90;
cout << ref(i) << endl;
}
// this works and prints 90.
int& ref(int q){
int a = q;
int &r = a;
return a;
}
main(){
int i=90;
cout << ref(i) << endl;
}
// warning and no output- warning: reference to local variable 'a' returned [-Wreturn-local- addr]
//same with pointers
int* poin(int q){
int a = q;
int *p1 = &a;
return p1;
}
main(){
int i=90;
cout << poin(i) << endl;
}
// this works and prints an address.
int* poin(int q){
int a = q;
int *p1 = &a;
return &a;
}
main(){
int i=90;
cout << poin(i) << endl;
}
// warning and no output- warning: address of local variable 'a' returned [-Wreturn-local- addr]
I'd really appreciate it if you could answer in simple terms as I'm not really that fluent in C++ yet.
I also want to ask the difference between returning &a
vs returning the pointer itself, and also the difference between returning the reference variable vs returning the original variable the reference variable was created for.