In C++, reference variable must be initialized. int &a; // Error
static int &b; // Error
But
extern int &c; // No error
Why Compiler doesn't give an error for extern specifier reference?
In C++, reference variable must be initialized. int &a; // Error
static int &b; // Error
But
extern int &c; // No error
Why Compiler doesn't give an error for extern specifier reference?
The extern keyword is a directive for the compiler that you are now declaring a symbol that will be filled in during linking, taken from another object file.
The initialization is EXPECTED to happen where the actual symbol is defined.
If you have an a.c file with
int foo;
int &bar = foo;
And a b.c file with
extern int &bar;
When you compile the file b.c into b.o the compiler will leave the symbol for bar empty. When linking the program, the linker will need to find the exported symbol bar in a.o and will then replace the blank symbol in b.o with the bar from a.o
If the linker can't find the required symbol anywhere in the linked object files - a Linker error (not compiler error) will be issued.
Why Compiler doesn't give an error for
externreference?
Because extern int &c; is not a definition, but merely a declaration. It's informing the compiler that c will be defined somewhere else in the program.
The cppreference page on "storage class specifiers" explains the meaning of extern in this scenario.
The language specification explicitly says
8.3.2 References
5 [...] The declaration of a reference shall contain an initializer (8.6.3) except when the declaration contains an explicitexternspecifier (7.1.1), is a class member (9.2) declaration within a class definition, or is the declaration of a parameter or a return type (8.3.5); see 3.1.
Your situation is directly covered by this quote. In other words, references are not excepted from the general declaration-definition rule. You can create a non-defining declaration for a reference defined (and initialized) elsewhere.
Nobody prohibits you from including an initializer into a reference declaration with an explicit extern keyword. However, as usual, it will turn a non-defining declaration into a definition.