What is local variables?

Local variable
What is local variable?

The variables that are declared inside the function are known as local variable. The variables declared in the header of the function definition are also treated as local variables of that function. The local variables can only be used in the function in which they are declared.

Local variables are also called the automatic variables. The keyword auto can be used to declared these variables. However, the use of auto is optional.

Scope of Local Variable
The portion of a program where a variables is used is known as scope. A local variable declared in a function can only be used in that function only.

Lifetime of local variable
The time period foor which a variable exists in memory is called lifetime of variable. Its lifetime starts when it is created in memory and ends when it is destroyed from memory. A variable can only be used during its lifetime.

The time period for which a local variable exists in memory is called lifetime of a local variable. The local variables are created when control enters into function. They are destroyed from memory when control returns back to calling function. When same function is called again, local variables are created again.

Example
#include <stdio.h>
Main(){
Int x,y,m;
Int max(int,int);
X=5;
Y=15;
M=max(x, y);
Printf(“maximum value is : %d” , m);
}
/*definition of max() function */
Int max (int a, int b)
{
Int mx;
Mx = (a > b) ? a:b;
Return mx;
}
In the above program, the variables “x”, “y” and “m” are declared inside the main() function. These are local variables for main() function and can be used in main() function. Similarly, the variables “mx” is declared inside “max” function and variables “a” & variable “b” declared in te function header are also local variables for “max”  function.
When the function “max” is called for execution, control will transfer to the function “max”. The variables “a”, “b” and “max” will be created into the memory. The value 5 will be assigned to variable  “a” and  15 will be assigned to variable “b”. When the control returens back after executing the statements of “max” function, the variables “a”, “b” and “mx” will be destroyed from memory.

What is local variables? What is local variables? Reviewed by JD Ahmad on June 18, 2018 Rating: 5

No comments:

Powered by Blogger.