title: Scope and lifetime of local variables in C
body: <p>I would like to understand the difference between the following two C programs.</p>
  
  <p>First program:</p>
  
  <pre><code>void main()
  {
      int *a;
      {
          int b = 10;
          a=&amp;b;
      }
      printf("%d\n", *a);
  }
  </code></pre>
  
  <p>Second program:</p>
  
  <pre><code>void main()
  {
      int *a;
      a = foo();
      printf("%d\n", *a);
  }
  
  int* foo()
  {
      int b = 10;
      return &amp;b;
  }
  </code></pre>
  
  <p>In both cases, the address of a local variable (<code>b</code>) is returned to and assigned to <code>a</code>. I know that the memory <code>a</code> is pointing should not be  accessed when <code>b</code> goes out of scope. However, when compiling the above two programs, I receive the following warning for the second program only: </p>
  
  <blockquote>
    <p>warning C4172: returning address of local variable or temporary</p>
  </blockquote>
  
  <p>Why do I not get a similar warning for the first program?</p>