A variable that is declared within the body of the function or block is called a local variable. This variable is used only within that block or function where it was created, other classes cannot access it. And is destroyed after exiting the block.
Properties of a Local Variable:
- A local variable is allocated on the C stack.
- Local variables are uninitialized by default and contain garbage values.
- The lifetime of a local variable is only within the function or block. And is destroyed after exiting the block.
- A local variable is accessed using block scope access.
Example: C Program for Local Variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> void differentFunc() { /*local variable of this function */ int a = 10; printf("%d : Variable from differentFunc function\n", a); } int main() { /*local variable of function main*/ int a = 50; { /*local variable for this block*/ int a = 30; printf("%d : Variable inside the block\n", a); } printf("%d : Variable of main\n", a); //calling function differentFunc(); } |
The output of Local variable in C:
1 2 3 | 30 : Variable inside the block 50 : Variable of main 10 : Variable of main |