It seems to me that a static class variable is identical to an extern variable, because you only declare it in the static int x
/ extern int x
statement, and actually define it elsewhere (usually in a .cpp file)
// .h file
class Foo
{
static int x ;
} ;
// .cpp file
int MyClass::x = 0 ;
// .h file
extern int y;
// .cpp file
int y = 1;
In both cases the variable is declared once somewhere, and defined in a file that will not be included more than once in the compilation (else linker error)
3.1. Static variables in C have the following two properties: They cannot be accessed from any other file. Thus, prefixes “ extern ” and “ static ” cannot be used in the same declaration. They maintain their value throughout the execution of the program independently of the scope in which they are defined.
static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files.
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
In terms of scope and extent, static variables have extent the entire run of the program, but may have more limited scope. A basic distinction is between a static global variable, which has global scope and thus is in context throughout the program, and a static local variable, which has local scope.
Yes, both have static storage duration and external linkage; they have essentially the same run-time properties, only differing in (compile-time) visiblity.
More or less. Both have external linkage, and static lifetimes. Both will be initialized on program start-up, and destructed on exit.
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