Variable
A variable is a name of memory location. It is used to store data. Value can be changed, and it can be reused many times.
It is way to represent memory location through symbol so that it can be easily identified.
Syntax : Data-Type Variable-Name;
Example
int a;
float b;
char c; Here a,b,c are variables.
Note : We can also provide values while declaring the variables.
Example
int a=10, b=20;
float f=20.2;
char c='B';
Types of variables
There are various types of variables are available in C programming language. which are discussed below :
1. Local Variable
A variable that is declared inside the function or block is called a local variable.It must be declared at the start of the block.
You must have to initialize the local variable before its first used.
The scope of local variable is always local. Means we can access from only inside the function.
Example
void function()
{
int x=10; // Local Variable
}
2. Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change the value of a global variable.
It must be declared outside of the block.
The scope of global variable is always global means we can access from anywhere through out the program.
Example
int value=10; // Global variable
void function()
{
int x=30; // Local variable
}
3. Static Variable
A variable that is declared with the static keyword is known as Static Variable. It retains its value between function calls.
Static variable can be defined inside or outside the function.The default value of static variable is zero.
Example
void function1()
{
int x=10; // Local Variable
static int y=15; // Static Variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
In the above example if you call the function many times, the local variable will print same value for each function but the static variable will print the incremented value in each function call.
4. Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. But if we want to explicitly declare a variable as an automatic variable then we can do with the help of auto keyword.
Automatic variables are similar as local variables.
Example
void main()
{
int x=10; // Local Variable
auto int y=15; // Automatic Variable
}
They both are automatic variables but the difference is that the y is explicitly declared as an automatic variable with the help of auto keyword.
5. External Variable
These variables are defined outside the function. We can share a external variable between multiple C files.External variables can be declared number of times but defined only once.
We can declare external variable with the help of extern keyword.Default value of external variable is zero.
No comments:
Post a Comment