-1

I tried to understand how c++ references work and I tried to write the next code:

#include <iostream>
int& func();
int main()
{
    std::cout <<func()<< std::endl;
    system("pause");
    return 0;
}

 int& func()
{
    int x = 23;
    return x;
}

for my understanding, the int x which was initialized in the function will be erased after the func ends and then the value that the function is returning will point to something that doesn`t exist. But when I print it I get 23 in the console. How does it possible?

Liroshka
  • 69
  • 9
  • 5
    [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) is undefined. – George Oct 27 '18 at 12:13
  • 1
    What did you expect? – n. m. could be an AI Oct 27 '18 at 12:14
  • I expected it to fail compiling because the value that the func returns is reference to something that dosen`t exists. can you explain where I am wrong? – Liroshka Oct 27 '18 at 12:22
  • 3
    If you crank up your compiler warning level (which you should do), and treat all warnings as errors (which is highly recommended), [you will get a warning/error in many such cases](https://godbolt.org/z/fh-0ok). But not in all cases. It is ultimately your responsibility to make sure you are not returning a dangling reference. The compiler cannot always ensure this. – n. m. could be an AI Oct 27 '18 at 12:36

1 Answers1

0

The value is written in the memory inside func(), but you are wrong in "doesn't exist" after return. Why would it not exist, did anything else overwrite that memory? You can't be sure. It's undefined behavior.

You are just returning a memory adress from func() which after return is made available for other variables. But if that (now available) memory adress is not overwriten, it will hold the value 23.. Until the end of days ;)

Here's @George 's reference to undefined behavior : https://en.cppreference.com/w/cpp/language/ub

Furthermore your code might have some errors... Anyway, look at this and it shall solve your worries Can a local variable's memory be accessed outside its scope?

niCk cAMel
  • 869
  • 1
  • 10
  • 26