Variable is like a container (storage space) with a name in which you can store data.
It is a way to represent memory location through symbol so that it can be easily identified.
The syntax to declare a variable is:
Data type variable_name;
The example of declaring the variable is given below:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a=10,b=20;// declaring two variable of integer data type
float f=18.7;
char c=’P’;
Rules to construct a valid variable name
- A variable name may consists of letters, digits and the underscore ( _ ) characters.
- A variable name must begin with a letter.
- ANSI standard recognizes a length of 31 characters for a variable name. However, the length should not be normally more than any combination of eight alphabets, digits, and underscores.
- Uppercase and lowercase are significant. That is the variable Tomatto is not the same as tomatto and TOMATTO.
- The variable name may not be a C reserved word (keyword).
Valid Variable Names:
int c;
int _lb;
int a80;
Invalid Variable Names:
int 4;
int c b;
int long;
Types of Variable
- Global Variable
- Local Variable
- Static Variable
Global Variable:
A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions.
It must be declared at the start of the block.
int value=20;//global variable
void function1(){
int x=10;//local variable
}
Local Variable:
A variable that is declared inside the function or block is called a local variable. Always it is declared at the start of the block.
void function1(){
int x=10;//local variable
}
You must have to initialize the local variable before it is used.
Static Variable:
A variable that is declared with the static keyword is called static variable. It retains its value between multiple function calls.
void function1(){
int z=12;//local variable
static int y=12;//static variable
z=z+2;
y=y+2;
printf(“%d,%d”,x,y);
}
If you call this function many times, the local variable will print the same value for each function call, e.g, 14,14,14 and so on. But the static variable will print the incremented value in each function call, e.g. 14, 16, 18 and so on.