Home » Learn C++ » Local Variables

Local Variables

Local Variables:

            The variables that arc declared inside the main function or inside any user-defined function are called local variables. These variables are also called the automatic variables. The keyword “auto” can he used to declare these variables. For example,

auto int a, b, c;
  

The use of keyword “auto” is optional. The variables used inside the functions are automatic by default.

 

Life-Time of Local Variables:

The lifetime of a variable is the time period between the creation and destruction of the variable. A variable remains available and can be used only during its lifetime.

            When the control is transferred to a function, the local variables or variables declared inside that function are automatically created and they occupy memory spaces to store data. When the control returns to the calling function or calling program, the variables of that function arc destroyed and their data is lost. Thus local variables can only he accessed from within the function in which they are declared. They are not available outside that function. The following program example explains the concept of local variables.

Program:

 

# include <iostream.h>

main ( )

{

int a, b, s;

int sum (int, int);

a = 10;

b = 100;

s = sum (a, b);

cout << “Sum = ” << s;

cout << “Ok”;

}

int sum (int x, int y)

{

int rs;

rs = x + y

return rs;

}

 

            In the above program the variables a, b and s are declared in the main function. These are local variables for the main function. The variables declared in the “sum” function are x, y and rs. The variables declared in function decelerator are also treated as local variables. When the function “sum” is called, control transfers to the function definition “sum”. The variables x, y and rs are created into the memory. The value 10 is stored in variable “x” and 100 in variable “y”. The sum of’ “x” and “y” is calculated inside the function definition and the result is returned to the calling function. When the control returns, the variables x, y and rs are destroyed from memory.

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.