A variable is a name of a storage location where data gets stored. Using that name one can perform operations and manipulations on the values.
Each and every variable has a lifetime to which extent it is visible within a particular block called scope, and outside of that block, the variable doesn’t have any existence.
These variables can be categorised in local, global and static.
In this article, we mainly focus on global and local variable.
Scope: A scope can be defined as an area to which a variable,method, class and interface is visible.
In C, if we compare local and global variable there are the following differences:
GLOBAL VARIABLE | LOCAL VARIABLE |
---|---|
A global variable can be accessed throughout a program | A local variable can only be accessed within a function or block in which it is defined |
A global variable, if not initialized, gets a default value | A local variable, if not initialized, holds an undefined value called garbage value |
Within a function, by default, if both global and local variable has the same name, the compiler would never refer to a global variable over a local variable | Within a function, by default, if both global and local variable has the same name, the compiler always refer to a local variable instead of global |
If there is any manipulation made it will visible to all the function | If there is any manipulation made it will noticeable only within the associated function |
It is is also known as an external variable | It can be termed as an automatic variable |
It gets fixed location, meaning no matter in which function it is being used | It may get a different location each time when calls to different functions are made |
It is defined outside the main function | It is defined within a function or a block |
No need to declare in every function | It is required to be declared each time for different function |
A local variable is declared inside a function or a block and its scope is always limited to that particular function or block. It remains alive until that particular block or function completes its execution.
Local variables are local to a block or function and go out of scope at the time exiting from the block or curly braces ({}).
Global variables is a variable that is accessible to entire program and is available to all the functions or blocks. It can be accessible to all the functions in a program.
Therefore, two or more variables can have same name but they must be in different scope.
#include <stdio.h> // Global variable int globalVariable = 10; int main() { // This variable can't be accessed in other functions int localVariable = 80; printf("I am Global Variable %d \n",globalVariable); printf("I am Local Variable %d ",localVariable); return 0; }
This post was last modified on October 6, 2020