1

In this code i has been defined (and it has been initialized despite being extern). Now the book I am reading says:

An extern declaration may be defined only if it appears to be outside a function.

and it offers no reason behind it.

#include<iostream>

using namespace std;

int main()
{
    extern int i=898;
    cout<<i<<endl;
    return 0;
}

I have gone through the question (similar to this one on Stack Overflow) but the explanation doesn't appear to be clear. The question is:

How are these two definitions different at function scope:

  1. int i=898;

  2. extern int i=898;

In both the cases a single unit of int size memory is being allocated. Is it due to linking error? Please answer clearly as (IMO) it hasn't been satisfactorily in older version whose reference has been used to mark this as duplicate.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • What are you trying to do? – Ed Heal May 01 '17 at 19:51
  • @EdHeal that line in the book caught my attention & hence this question was asked. –  May 01 '17 at 19:52
  • 2
    One is legal (and therefore means something) the other one is illegal (and therefore doesn't mean anything). – David Schwartz May 03 '17 at 19:38
  • The `extern` says 'the variable is defined somewhere else' (and specifically, not in this function); you can't control how that variable defined somewhere else is initialized — the somewhere else that defines the variable may have different views on how it should be initialized. – Jonathan Leffler May 03 '17 at 19:53
  • Maybe it's similar to extern const that might have an initializer to be used in constant folding. – Daniel May 03 '17 at 19:54
  • @DavidSchwartz How is extern int i=898; illegal as it is allowed to be done outside a function (which throws a warning). –  May 05 '17 at 02:53
  • @infinite What do you think it should mean? The reason it's not legal is because there is nothing sensible for it to mean. – David Schwartz May 05 '17 at 08:29
  • @DavidSchwartz can you please confirm this (this line is from one of the answers) -> "The extern keyword keeps the compiler from allocating memory for the variable indicating that memory for the variable will be resolved at link time in global scope.". It this happens, is it despite using initializers with extern? –  May 06 '17 at 04:22
  • @infinite The `extern` keyword means different things in different contexts. That is the gist of the idea it expresses, but it's not a precise explanation that applies to every use. – David Schwartz May 06 '17 at 20:03

1 Answers1

0

The extern keyword keeps the compiler from allocating memory for the variable indicating that memory for the variable will be resolved at link time in global scope. Your link to the other answer was not available so I answered.

jiveturkey
  • 2,484
  • 1
  • 23
  • 41