Concept of a variable
A variable contains a value that is given by a user. It makes the programmer easier to use variables rather than using memory locations and makes the program readable. Variable is an alternative name for the memory location.
Certain rules to be followed while naming variables are as follows:
- They must begin with a letter or underscore but must not start with a digit.
- They must include only letters, digits, or underscore.
- No other special character or symbol is allowed.
- It should not be a keyword.
- It must not contain white space.
- Variable name should be unique.
- Maximum length of a variable can be 31 characters but only the first 8 characters are important.
- Upper case and lower case are significant.
Some examples of C variables:
adc – Valid
X11- Valid
A%B – Invalid as it contains a special character other than the underscore.
int – Invalid as it is a keyword.
X z – Invalid as it contains a white space.
_xy9_a3 – Valid as a variable name can also start with an underscore and can go with any combinations of letters and digits or again an underscore.
Variable Definition:
While defining a variable, the name and data type of the variable is indicated to the compiler. The compiler allocates memory to the variable in the storage space depending on the size specification of the variable.
General form:
data_type var1, var2,..varn;
Example:
int a; float x,y; char m,n,p;
After variable definition, a variable may be used within the program depending on the scope of that variable.
Declaration of variable:
Declaration introduces variables in the program whereas definition directs the compiler to allocate memory for the variable. The variable declaration informs the compiler of the existence of a variable of a particular type and name. A variable declaration may occur several times, but the variable definition occurs only once in a program, or this would result in a waste of memory.
Variable Initialization:
Assigning some value to the variable is variable initialization. Initialization of a variable and declaration can be done on the same line.
Example:
int ip=356;