C Variable Scope

Variable in C differ in behaviour from those in most other language.In C not do all variable have a data-type,they also have a storage class.The following variable storage classes are most relevant to function:-

  1. Local Variable
  2. Global Variable
  3. Static Variable
  4. Register variable

In this tutorial, We discuss the scope and visibility of each of the above class variables.

The Scope of the variable determines over what region of the program a variable is available for use while visibility refers to accessibility of a variable from the memory. It is very important to understand the concept of storage classes and their utility in order to develop the efficient multifunction program.

Automatic (Local) Variable

C Code Example

These are declared inside a function in which they are to be utilized. They are created when the function is called and destroying automatically when the function is exited, hence the name is automatic(Local). This assure that we may use declare and use the same variable name in different functions in the same program without causing any problem to the compiler.

We may also use Keyword auto to declare Local variable:-

External(Global) Variable

C Code Example

These variables can be accessed by any function in the program. These are active in the entire program thats why it is known as External or global variables. These are declared outside a function.

Static Variable

The value of the static variable persists until the end of the program. A variable can be declared static using the keyword static. A general form is:-

static data_type variable_name;

Register Variable

We can tell the compiler that a variable should be kept in one of the machines registers, instead of keeping the memory. Since register access is much faster as compared to memory access. keeping the frequently accessed variable(for example-loop control variable)in the register. A general form is:-

register data_type variable_name;

Since only a few variables can be placed in the register, it is important to carefully select the variable for this purpose. However,C will automatically convert the register variable into a non-register variable once the limit is reached.