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.
Syntax:
type variable_name;
Example:
int length, width = 10;
float value;
Rules for naming a variable
- The first character of an variable should be a alphabet(a-z , A-Z) or underscore (_).
- Keywords are not allowed to be used as variable.
- Variable should not be of length more than 31 characters.
- Commas or spaces are not allowed within an identifier.
- Variable are case-sensitive so UPPERCASE and lowercase are treated as different name. For example: APPLE, Apple and apple are three different variable.
Declaration of a Variable
Declaration of a variable is about telling a compiler about the existance of the variable. But in this case no memory is allocated for the variable.
Syntax for declaring a variable:
extern type variable_name;
Example:
extern int x;
In the above example we declared a variable named x
of type integer
. In this stage compiler will keep the record of the existance of variable x
but will not allocate any memory space.
Defining a Variabe
For using any variable we need to define it first so that the compiler knows about the existance of it and allocate memory for it. If we are defining a variable then there is no need to declare it.
Syntax for Defining a variable:
type variable_name;
Example:
int ojhabikash;
float ojha;
Initializing a Variabe
If you want the variable to have some initial value then Initializing it is the best approach.
Syntax for Initializing a variable:
type variable_name = value;
Example:
int ojhabikash = 10;
Program example of variables in C
//An example of variables in c
#include<stdio.h>
int main()
{
int length = 10, width = 5, area; //declaration, definition and initialization
area = length*width; //assigning a value
printf("Area is = %d \n", area); //using of variable
return 0;
}
Area is = 50