Local and global variable in C plus plus and C language

Local and global variable in C plus plus and C language
In C language and C plus plus language the local and global variables are used as in same method.
Variables are classified in two categories that is one Global variable and another one is local variable.
lacal variable, gloable variable,
C language

1-Local variable:- 

Identifiers are declared as level, constant, type, variable and functions block are said to belong to a particular block or function and these identifiers are known as local variables or parameters.

local variables are defined inside a function block or a compound function.

Example:-
void function (int i, int k)

{

int m, n; // local variables

---------------------------------------

---------------------------------------

// body of the function.

}

The integer variables m and n are defined within a function block for the function().
all the variables to be used within a function block must be further defined at the beginning of the block itself or before using in a statement. local variables are referred only the particular part of the block or a function. same variable name may be given different part of a function block and each variable will be treated as a different entities.

Example:-

function1( float a , float b)

{

float m, n; // local variables.

m=10.5;

n=11.5;

-----------------------------------------

-----------------------------------------

//Body of the function1.

}

function2 (int i, int k)

{

float m, n; // local variable of function2

m=10.555;

n=11.555;

------------------------------------------

------------------------------------------

//body of the function 2

}

Some special and important program of c language and c++


2- Global variable in C ++


Global variables are variables defined outside the main function block. These variables are referred by the same data type and by the same name through out the program in both the calling portion of the program and in the function block. whenever some of the variables are treated as constant in both the male and the function block, it is advisable to use Global variables.

for example:-

int m, n=10; // Global variable declaration

void main (void)

{

Void function1()

x=20;

------------------------------------------

------------------------------------------

function1();

}

Function1()

{

Int sum;

sum=m+n;

-----------------------------------------

-----------------------------------------

}

Program example-

1-Write a program to find the sum of given two numbers using the Global variable declaration.

//Global variable declaration here

# include<iostream.h>

int x;

int y=5;

void main (void)

{

x=10;

void sum( void)

sum();

}

Void sum (void)

{

int sum;

sum=x+y;

cout<<” x=” << x<<endl;

cout<<”y=”<<y<<endl;

cout<<”sum=”<<sum<<endl;

}

Output of the above program

x=10

y=5

sum=15

Post a Comment

0 Comments