What are the Scope Rules of Variables in C Language with Free Notes

Scope Rules of Variables

Scope Rules – The range of the code in a program over which a variables has a meaning is called as scope of the variables. In simple form, the scope of variables decides as to how it can be accessed by the different parts of the program.

There are three types of scope normally in C:

  1. Local Scope
  2. Function Scope
  3. File Scope and Global Scope

Types of Scope Rules

Here we define the all the types of Scope Rules,

Local Scope

A block of statement in C is surrounded by curly braces i.e. { and }. We can declare variables inside the block, such as variables called as local, can be referenced only within the body of the block.

When the control reaches open braces, these variables comes into existence and get destroyed as soon as the control leaves the block through the closing brace.

So the local variables are available to all the blocks enclosed by the block in which they have been declared.

while (flag)
{
      int x;
      if ( i > x)
            {
               int j;

               -
             }
 }
  • The scope of x is the while block, and j is if block.
  • The variable x can also be referenced to in the if block because this block is completely enclosed in the while block.
  • On the other hand, scope of j is only the if-block. Since a function is a block in itself, all the variables declared in, it has the local scope.
  • The formal parameters in function has local scope.

Function Scope

  • The function scope pertains to the labels declared in a function in the sense that a label can be used anywhere in the function in which it is declared.
  • Thus we can use different labels with same names in different functions.

File Scope or Global Scope

Since the global variables are declared outside all blocks and functions, they are available to all the blocks and functions.

Thus the scope of a global variable is in the entire program file. This type of scope is known as file scope.

e.g. global variable rate and qty of the following has file scope

int qty, rate;
void main ()
{
   int gross, net;
     -
}
fun()
{
    char c;
      -
   { 
       int a;
         -
   }
}

The scope rules can be summarized as below:

  1. A local variables can be accessed only within the block in which it is declared. The local variable declared in a function exists only during the execution of the function. Therefore these variables are also known as automatic because they automatically created and destroyed.
  2. The scope of formal parameters is local to the function in which it is defined.
  3. Since the global variables are not declared in a a particular function, they are available to all the functions. Thus the scope of a global variables is in the entire program.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top