0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
abdullah
  • 9
  • 5
  • 1
    you've simply defeated the compiler's analyser, its just as undefined behaviour in both cases. You might also just need to update your compiler, gcc does issue a warning for your code https://godbolt.org/z/75T3oKjKh – Alan Birtles Sep 30 '22 at 08:39
  • It doesn't work. It has Undefined Behaviour. You are not guaranteed *anything*. Please read https://en.cppreference.com/w/cpp/language/ub (including the great articles linked at the end). Just because something *compiles* does not mean that it is valid. – Jesper Juhl Sep 30 '22 at 08:40
  • Also refer to [Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?](https://stackoverflow.com/questions/49032551/why-is-the-phrase-undefined-behavior-means-the-compiler-can-do-anything-it-wan) – Jason Sep 30 '22 at 09:28
  • `main(){}`: this is not valid C++, all function declarations must include return type. – prapin Sep 30 '22 at 10:28

0 Answers0