A variable is a name assigned to some storage area in a memory allocated to it. In other words a variable is a value which can be altered during the program execution.
There are mainly two types of variables in C :
- Local variables
- Global variables
Local variables
Local variables are those variables that are contained within a block of statements grouped together called as functions. The local variables have scope within that function only which means a local variable cannot be accessed outside that function where it is defined.
Program example of local variables
//An example of the local variable
#include<stdio.h>
int main()
{
int var = 10;
printf("This is a local variable var = %d \n", var);
return 0;
}
Output
This is a local variable var = 10
In the above example var
is a local variable and can’t be accessed outside the main() function.
Global Variables
Global variables are those variable that are declared or defined outside the functions. It is mostly placed at the beginning of the program code. The global variables have the global scope which means it can be accessed anywhere within the program.
Program example of global variables
//An example of the local variable
#include<stdio.h>
int myVar = 10;
void myFunc()
{
printf("Global variable accessed through user-defined function, myVar = %d \n", myVar);
}
int main()
{
printf("Global variable accessed through main function, myVar = %d \n", myVar);
myFunc();
return 0;
}
Output
Global variable accessed through main function, myvar = 10
Global variable accessed through user-defined function, myvar = 10
In the above example myVar
is a global variable and it is accessed in main() as well as myFunc() function.