Quick links
Local variables are variables declared within a function or more specifically say within a block.
Block is a sequence of statements grouped together inside a pair of curly braces {
and }
. Since the first day of programming, you have been using blocks. For example – if…else block, loop block, function block etc.
Properties of a local variable
- A local variable is allocated on C stack.
- Local variables are uninitialized by default and contains garbage value.
- Lifetime of a local variable is until the function or block. A local variable dies once the program control reaches outside its block.
- Local variable is accessed using block scope access.
Block scope access
Block scope states that, variables declared inside a block can be accessed only within same or inner blocks. Block inside a block is called as inner or nested block.
Following are various accessibility rules of a variable defined by block scope.
- You can access a variable only within same or its inner block. For example –
Output of the above program.
- You can declare two or more variables with same name in different blocks. However, you cannot declare more than one variable of same name within same block. For example –
In the above code I have commented the re-declaration of
int num
. As the program won’t compile if you remove comments. - Inner block shadows outer block variable if both declared with same name. If both inner and outer block variable is declared with same name, then you cannot access outer block variable with same name inside inner block. For example –
Output of the above program.
- Variables declared within inner block are not accessible to outer block. For example –
In the above program sum is declared inside inner block and can’t be accessed outside its block.
Local variables best practices
You have been using local variables since the first day of programming in C. However, always follow these best practices to avoid errors in your program.
- Always try to minimize the usage of variables with same name within outer and inner block to avoid ambiguity. In addition, variables declared with same name within outer and inner blocks are complex to read and trace errors.
- It is a good programming practice to initialize local variables before use to override its garbage value.