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

 Live Demo

#include <stdio.h>
int s;
int main () {
   int a = 15;
   int b = 20;
   s = a+b;
   printf ("a = %d
b = %d
s = %d
", 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

 Live Demo

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

Output

a = 35
b = 20

Updated on: 24-Jun-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements