Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to specify type of extern/ static variable at initialization?

Tags:

c++

static

extern

I do not understand the need to specify the type of an extern/static variable at initialization. For example:

struct Test{
 static int i;
};
 Test::i = 2; //error
 int Test::i = 2; //ok

Doesn't the compiler know that i is of type int? Is it just a particularity of the compilers, or why is specification of the type,,int" needed?

like image 914
Ganea Dan Andrei Avatar asked Apr 17 '15 14:04

Ganea Dan Andrei


1 Answers

I do not understand the need to specify the type of an extern/static variable at initialization.

Because the language designers chose to use the same syntax for variable declarations and definitions. That syntax includes the type name. You're correct that, in some cases, that type name is redundant. But allowing you to leave it out might be somewhat confusing: it would look like an assignment, not a definition.

Doesn't the compiler know that i is of type int?

Only if the variable has already been declared. That has to be the case for a static member like this, but not necessarily for a global variable. You could declare it in one source file:

extern int i;

and define it in another

int i = 42;

without making the declaration available to the definition.

like image 110
Mike Seymour Avatar answered Oct 21 '22 17:10

Mike Seymour