In this tutorial you will learn about the C Scope Rules and its application with practical example.
The c scope rules define the region of visibility or availability for a variable, out of which we can not reference that variable. There are two main kinds of c scope rules:
- global
- local
Global Variable
Global variables can be accessed at any point throughout the program and can be used in any function. There is a single copy of the global variable is available. Global variables are defined outside of all the functions, usually on top of the program.
Local Variable
Variables declared inside a function or block of code are called local variables. They can be accessed only inside that function or block of code. Local variables are not available to outside functions.
Example Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> /* global variable declaration */ int sum; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; sum = a + b; printf ("value of a = %d, b = %d and sum of (a and b) is = %d\n", a, b, sum); return 0; } |
Note:- A program can have the same name for local and global variables but the local variable overrides the value.