In a program, we typically do lots of calculation. Thus these calculated results are stored in computer memory while computer memory consists of millions of memory cells. These cells are also called as memory locations. Each memory location has their names called as variable names ( C Variables ). The value stored in each location may change.
Definition of Variable
- Variable is a container which will hold value. These value can be used during the execution of the program.
- Only one value can be stored in a single variable.
- Variable of different data type is used to store different types of data.
- Variable is a name given to memory location (storage area).
- Variables names are names given to locations in memory.
- These locations can contain integer, real or character constants.
- For example, Integer variables are used to store integers. Character variables are used to store characters etc.
Variable Declaration
Syntax
1 2 3 |
data_type variable_name; OR data_type variable_name1, variable_name2, variable_name3; |
Variable Initialization
1 2 3 |
data_type variable_name = value; OR data_type variable_name1 = value, variable_name2 = value, variable_name3 = value; |
Example
1 2 |
int number; //stores an integer number float number1; //stores decimal number |
number and number1 are different variables located at a different memory location. No two variables will have same memory location.
Here number, number1 are variables of data_type int and float.
Rules for Constructing Variable Names
- A variable name can be consist of letters (a-z, A-Z), digits (0-9), or underscore (_).
- The variable name must not start with a number, it must start with alphabet or underscore.
- No blank spaces or commas or any other special symbol (#, $, etc) other than underscore are allowed within a variable name.
- Maximum allowable length of a variable name is 31 characters.
- C keywords cannot be used as variable name.
- Variable names are case-sensitive.
Types of variables
There are mainly two types of variables in C language depending on the scope of access.
What is a difference between variable declaration and variable definition?
A declaration introduces an identifier and describes its type.
A declaration is what the compiler needs to accept references to that identifier.
Example
1 |
int number; //this is declaration of variable |
A definition actually instantiates identifier. It’s what the linker needs in order to link references to those entities.
Example
1 |
int number = 5; //this is defination of variable |
A variable declaration must be done in above the program.
And the variable definition is within the program.
A variable definition can be used directly in place of variable declaration.
The declaration is for the compiler to accept a name. The definition is where a name and its content is associated.
The definition is used by the linker to link a name reference to the content of the name.
Declarations can occur more than once in a program.