12. Scope rule in C

There are three variable scope in C-Language

  • Global variables
  • Local variables
  • Formal parameters

 

Global variables:

  • Global variables can be accessed anywhere in a program.
  • The scope of the global variables are global throughout the program.
  • Any function can access and modify value of global variables.
  • Global variables retains their value throughout the execution of entire program.
  • Global variables are initialized by the system when you define. Global variables of data type int, float and double gets initialized by 0 and pointer variables gets initialized by NULL.
  • We can use same name (identifiers) for local and global variables but inside a function value of local variable gets priority over global variable.
/* Global variable declaration */ 

int x; 

int main(){ 

//Main code 

}

 

Local variables:

  • Local variables can only be accessed by other statements or expressions in same scope.
  • Local variables are not known outside of their function of declaration or block of code.
  • Local variables gets created every time control enters a function or a block of code. When control returns from function or block of code, all local variables defined within that scope gets destroyed.
  • Local variables contains garbage values unless we initialize it.
int main () {

/* local variable declaration */

int a, b;

int c;

// Main code

}

In above example ‘a’, ‘b’ and ‘c’ are local variable.

 

Formal parameters:

Formal Parameters in C are the arguments which is used inside body of function definition. Formal parameters are treated as local variables with-in scope of that function. It gets created when control enters function and gets destroyed when control exits from function. Any change in the formal parameters of the function have no effect on the value of actual argument. If the name of a formal parameter is same as some global variable formal parameter gets priority over global variable.

#include <stdio.h>

/* global variable declaration */

int a = 20;

int main () {

/* local variable declaration in main function */

int a = 10; int b = 20; int c = 0;

printf ("value of a in main() = %d\n", a);

c = sum( a, b);

printf ("value of c in main() = %d\n", c);

return 0; }

/* function to add two integers */

int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);

printf ("value of b in sum() = %d\n", b);

return a + b; }

 

Questions