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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With