Variable scope and storage class are 2 different things.
Scope indicates where in the code you may use a variable
storage class indicates where in memory the variable is stored.
I would say there are 3 variable scopes, 4 if you include prototype-scope but that that doesn't seem useful to me
- Program Scope: A variable that is declared outside of all code blocks and is not declared static is accessable from any part of the program (although use of an extern statement will be required).
- File Scope: A variable that is declared outside of all code blocks and is declared static is accessable from any part of the file following the declaration.
- Local or Block Scope: A variable declared inside a code block is only accessable within that block. The parameters of a function are consider to have local scope as if they had been decared inside the block enclosing the function body.
- Prototype Scope: variables declared with-in a prototype have scope only up to the end of the prototype. meaning that for
int Multiple(int x, int y);
int Add(int x, int y);
because x and y have prototype scope because they are out of scope at the end of Multiply you don't have a problem when you use them again in Add.
Function scope does exist but only applies to labels. They may be used anywhere inside the function but not externally to the function so
-
void fn()
-
{
-
goto TheLabel;
-
-
if (someCondition)
-
{
-
-
TheLabel:
-
}
-
}
-
works because TheLabel has function scope is accessable anywhere inside the function.
For C++ there is also Class Scope, variable declared in the class are accessable only within the class.
Storage Class can basically be extern, static, auto or register.
extern and static storage classes declare variables with global lifetime, the exist for the lifetime of the program.
auto and register declare variable of local lifetime, the only exist while the current code block executes.
The default storage type inside a code block is auto so you rarely see this keyword in code as it can be left out.
Register is also not common any more. It is a instruction to the compiler to dedicate a processor register to store the variable rather than using RAM. This would be used to optimise code for speed of execution. Since the advent of good optomising compilers it is generally considered better not to use this key word and to give the optomiser free reign to select whatever optomisations are best.