title: Return By Reference to Local Reference From Function
body: <p>I started studying C++. I didn't understand return by reference. In the following code we have a local variable <code>i</code> inside the function <code>getInt()</code>. The scope of <code>i</code> is dependent on <code>getInt()</code>. when we get out of <code>getInt()</code> the variable <code>i</code> will be gone. If we use the following function, we will have a segmentation fault because we are returning a reference to a variable that don't exist anymore.</p>
  <pre><code>int&amp; getInt() {
      int i = 10;
      return i;  
  }
  </code></pre>
  <p>what I didn't understand is that how come when I assign <code>i</code> to a reference and return that reference I managed to get the right value which is <code>10</code>. Aren't we returning a reference to a variable that will be destroyed after we exist the function?</p>
  <hr />
  <pre><code>// Online C++ compiler to run C++ program online
  #include &lt;iostream&gt;
  
  int&amp; getInt() {
      int i = 10;
      int &amp;x = i;
      return x;  
  }
  int main() {
      int &amp;x = getInt();
      std::cout &lt;&lt; x &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>