title: Why does initializing an extern variable inside a function give an error?
body: <p>This code compiles fine:</p>
  
  <pre><code>extern int i = 10;
  
  void test()
  {
      std::cout &lt;&lt; "Hi" &lt;&lt; i &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>While this code gives an error:</p>
  
  <pre><code>void test()
  {
      extern int i = 10;
      std::cout &lt;&lt; "Hi" &lt;&lt; i &lt;&lt; std::endl;
  }
  </code></pre>
  
  <blockquote>
    <p>error: 'i' has both 'extern' and initializer</p>
  </blockquote>
  
  <p>I read this in <a href="https://rads.stackoverflow.com/amzn/click/com/0321714113" rel="noreferrer" rel="nofollow noreferrer">C++ Primer</a>:</p>
  
  <blockquote>
    <p>Any declaration that includes an explicit initializer is a definition.
    We can provide an initializer on a variable defined as extern, but
    doing so overrides the extern. An extern that has an initializer is a
    definition. <strong>It is an error to provide an initializer on an extern inside a
    function</strong>.</p>
  </blockquote>
  
  <p>Can someone provide an explanation as to why this is an error if done locally in a function, while the same is allowed at a global scope?</p>