What is a Local Variable?
- Local variable is a variable which is recognized only with in a single function.
- Normally local variables does not retain its value once control has been transferrd out of the function.
- Global variaables can be recognized in two or more functions.
- Global variables retain its value until the program terminated.
- Storage class are used to define the scope (visability) and life time of variables and/or functions in a program.
- Scope refers to the portion of the program over which the variable is recognized.
- There are 4 different storage classes in C
- Automatic Variable
- External Variable.
- Static Variable+
- Register Variable
- Always declared with in a function and are local to the function in which they are declared .
- The keyword is auto.
- Example:
auto int a,b,c;
- The default storage class is auto. So if we declare int x;. It refers to auto int x;
- Automatic variables defined in different functions will be independent of one another eventhough they have the same name
Automatic Variable Example main() { auto int a,b,c; ----------------- ----------------- fun1(); ------------------- } fun1() { int a,b; ----------------- }
In the above example the variables a,b,c declared in the main function is available only to the main function and the variables declared in the function fun1() is local to the function - Automatic variables can be initialized during the variable declaration or explicit assignment statement
Example:
auto int x=10; is same as auto int x;
x=10; - If the variable is not initialized its initial value will be unpredictable.
- The assigned value will be reassigned each time the function is reentered
- An automatic variable does not retain its value once control is transferred out of its defining function.