The code is throwing error despite 'i' being defined after initialization, why?
Code:#include<iostream> using namespace std; int main() { extern int i=898; cout<<i<<endl; return 0; }
The code is throwing error despite 'i' being defined after initialization, why?
Code:#include<iostream> using namespace std; int main() { extern int i=898; cout<<i<<endl; return 0; }
extern means that the variable defined elsewhere, possibly further down in the same file, but usually in another source file (and therefore object file). Since extern used on a variable does not define the variable, you cannot initialize it there. Here is one possibility that will compile.
Code:#include <iostream> using namespace std; int main() { // tell compiler about existence of i that will be defined elsewhere extern int i; cout << i << '\n'; return 0; } // define the variable (could be in another source file) int i = 898;
Initializing an extern variable defines that - the question is why definition - extern i =898; is different from definition - int i =898;Since extern used on a variable does not define the variable, you cannot initialize it there.
Check this out:
This works fineCode:#include <iostream> using namespace std; extern int k =89; int main() { cout<<k; return 0; }
That throws a warning for me:
Source:Code:$ g++ -Wall -pedantic -O0 -g -std=c++14 main.cpp main.cpp:3:12: warning: ‘k’ initialized and declared ‘extern’ extern int k = 898; ^
Since it throws a warning, i would not count on it working the way you think it works.Code:#include <iostream> extern int k = 898; int main (int argc, char* argv[]) { std::cout << k << std::endl; return 0; }
This warning can only hide a linker error of multiple definition which doesn't stand in this case. focus on this: how these definitions: int K=898 & extern int K=898 are different at function scope.
In 2.2.2. Variable Declarations and Definitions of c++ Primer 5th ed Lippman et.al. I came across this rule:
i.e. trying to define an external variable inside of a function is not allowed, which makes sense. But you can declare it there so that it can be used there.It is an error to provide an initializer on an extern inside a function.
The reason behind it is not given hence the question is asked.
Yes, I agree it would be more satisfying had they quoted the standard or gave a reason for that rule.
Here is some reasoning:
Those 'extern' variables are initialized before any function runs.
see Non-local variables at:
Initialization - cppreference.com
If it was declared 'static' rather than 'extern' within a function block, it would still have static storage duration, but its' linkage would be local to that function vs. external. So would get initialized when the execution first runs through that line within the function:
Storage class specifiers - cppreference.com
Last edited by dslowik; 05-07-2017 at 01:23 PM. Reason: Added spacing