static is not the "opposite" of extern. static variables have very special properties. There are different ways to use a static variables:
1- In class defintions: static variables have a single value along all the instantiations of the class, and do not require an object of a class to be used, and btw, they are initialised automatically, so you don't have to worry about initialising them. For example:
1 2 3 4
|
class MyClass
{
static int x;
};
|
Now to access x, you don't have to have an object of MyClass, you can simply do this:
You can use static variable in classes, for example, to count how many instances of a class are present.
And not to mention, that static methods in a class can be called without instantiating a class object, as well.
2- In functions: static variables in functions do not depend on the function scope. This means, if you call a function once, and you call it again, the same value of the static variable will remain unchanged.
In general, static means the variable is independent of every scope in the program. This is very useful when you wanna avoid using global variables (which is really a bad style compared to static variables and functions).
extern is simply another name for global variables.