Computer >> Computer tutorials >  >> Programming >> C programming

Scope Rules in C


In C language, scope is a region of program where identifiers or variables are directly accessible.

There are two categories of scope rules in C language.

Global Variables

Global variables are declared and defined outside any function in the program. They hold their values throughout the lifetime of program. They are accessible throughout the execution of program.

Here is an example of global variables in C language,

Example

#include <stdio.h>
int s;
int main () {
   int a = 15;
   int b = 20;
   s = a+b;
   printf ("a = %d\n b = %d\n s = %d\n", a, b, s);
   return 0;
}

Output

a = 15
b = 20
s = 35

Local Variables

Local variables are the variables which are declared and defined inside a block or function. They can be used only inside that block or function.

Here is an example of local variables in C language,

Example

#include <stdio.h>
int main () {
   int a = 15;
   int b = 20;
   a = a+b;
   printf ("a = %d\n b = %d\n", a, b);
   return 0;
}

Output

a = 35
b = 20