Scope and Extent in C Programming Part-3



LOCAL AND GLOBAL VARIABLES:
              The variables in general may be classified as local or global variables.





1. LOCAL VARIABLE:
              The term local means that the variables are private to that particular function and are distinct from other variables of the same name declared elsewhere in the program. For example:
function (a, b)
int a, b;
{   int x, y;    /*local variables  */
/*  body of the function   */   }
              The integer variable x and y are defined within a function block of the function(). All the variables to be used within a function block must be defined at the beginning of the block itself. The local variables are referred only to the particular part of the block or a function. The same variable name may be given to a different part of a function or a block and each of the variables will be treated as a different entity. For example
function1 (a, b)
float a, b;
{    float x, y;    /*  local variables  */
x = 10.101;
y = 20.20;
-------------
-------------
/*   body of the function1  */    }

function2 (I, j)
int i, j;
{   float x, y;    /*  local to the function2  */
x = 1.11;
y = 2.28;
/* body of the function2  */   }





2. GLOBAL VARIABLES:
             Global variables are defined outside the main function block. These variables are referred to by the same data type and the same name throughout the program in both calling portion of program and a function block. Whenever, some of the variables are treated as constant in both the main and the function block, it is advisable to use global variables. For example:
 int x, y = 4;    /* global declaration  */
main()
{    x =10;
------------
------------
function1();   }
function1()
{  int sum;
sum = x + y;
---------------
---------------    }
           Here, x and y are declared as global variables and used by the function2().
EXAMPLE:
          Write a program to find sum of given two numbers using global variable declaration.
#include <stdio.h>
int x, y = 2, sum;
main()
{  int function(int);
x = 4;
function(sum);   }
function (int sum)
{ 
sum = x + y;
printf (" %d + %d = %d \n", x, y, sum);    }
Output:

Scope and Extent in C Programming Part-3  Scope and Extent in C Programming Part-3 Reviewed by vijay pratap singh on July 13, 2017 Rating: 5

No comments:

Powered by Blogger.