Scope Rules in C

By | August 27, 2020

The scope of a variable x is the region of the program in which uses of x refers to its declaration. In C, all identifiers are lexically(or statically) scoped.

Scoping in C is generally divided into two classes: Static Scoping, and Dynamic scoping.

Static Scoping :

Static scoping is also called lexical scoping. Static scope refers to the scope of variable that is defined at compile time. It is always refers to the variable with top level environment. Static scoping also makes it much easier to make a modular code as programmer can figure out the scope just by looking at the code. Binding of a variable can be determined by program text and is independent of the run-time function call stack.

Dynamic Scope :

With dynamic scope, a global identifier refers to the identifier associated with the most recent environment, and is uncommon in modern languages. Dynamic scope refers to scope of a variable that is defined at run time. It refers to the identifier with the most recent environment.

When a variable is referred in program we should follow the following priority to associate its value

In static scoping we can associate scope of the variable during compile time. And in Dynamic scoping at run time.

Example –

#include<stdio.h>

// global variable
int y = 5;

int fun1() {
    
    // it accesses global variable y
   int x = y + 5;
   printf("%d\n",x);
}

int fun2() {
    
    // local variable
   int y = 2;
   return fun1();
}

int main()
{
   fun1(); 
   fun2();
   return 0;
}

This above will be print 10, 10 according to static scoping, and 10, 7 in dynamic scoping.

Notes :

  • Local variables are the variables that are declared inside a block or a function. These variables can only be used inside that block or function.
  • Global variable is the variable that is declared outside of a block or function. These variables can be accessed from anywhere in the program.



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.