-1
extern int eg_i = 0;

int main(){
++eg_i;    // 1
return 0;
}

This code surprisingly throws no compile error.

Because if an extern variable is declared with initialization, it is taken as the definition of the variable as well.

I didn't know there's an exception for the extern keyword.

GamerCoder
  • 139
  • 6
  • I can't see any undefined variables in the sample code – The Dreams Wind Aug 28 '22 at 21:37
  • *"the 'eg_i' increases everytime 'test' being called."* -- that is bizarre, considering that `eg_i` is not used anywhere (which could explain the lack of a link error). Did you copy-paste your code, or did you try to re-type it and introduce typos in the process? Definitely prefer the former. – JaMiT Aug 28 '22 at 22:19
  • C++ should be learnt using a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of by trial and error. In particular, `extern int eg_i = 0;` is a definition which is explained in any beginner level c++ book. – Jason Aug 29 '22 at 13:05

1 Answers1

1

This declaration

extern int eg_i = 0;

is a definition of the variable eg_i because there is present an initializer.

So there is no problem.

From the C++ 17 Standard (6.1 Declarations and definitions)

2 A declaration is a definition unless

(2.2) — it contains the extern specifier (10.1.1) or a linkage-specification26 (10.5) and neither an initializer nor a function-body,

By the way it seems there are typos within the function test. It should look like

void test(){
++sgi;
++egi
++eg_i;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335