What is Scope of variables?
Scope describes how widely visible a name is in a file (translation unit). Linkage describes how a name can be shared in different units. A name with external linkage can be shared across files and a name with internal linkage can be shared by functions within a single files.
There are several scopes:
Local variables: The variable which is declare inside the class or function is local variable. In local variable user should initialize the variable. Otherwise it will show an error.
For Example:
int main( )
{
int i=0; //local variable
printf(i);
}
Register Variable: A register variable is another form of automatic variable. So it has automatic storage duration, local scope and no linkage. The register keyword is a hint to the compiler that you can provide fast access to the variable.
For example:
register int count_objects; // request for a register
*Note: ‘Register’ is just a “hint” and “request” for local variable.
Static Variable: Static variable have three kinds of linkage: external linkage, internal linkage and no linkage. Statics variable works as global which is always outside the function or method but inside the class. If we did not initialize the variable then its default value become zero. We should write static keyword for making variable static.
For example:
int global=1400;
static int one_file=25; //static variable
int main( )
{ …..
}
External variable: External variable is variable which is declare outside function. We can use that variable anywhere inside the program. we should write the word extern for making method or variable external.
For example:
extern int foo(int arg1, char arg2);
int main( )
{…}
Note that : There are mainly three scope:
Local(Register variable is used for request local variable),
statics and
global.