A variable is a named location in memory that is used to hold a value of a particular data type that value can be changed by program. Every variable has a name and value. There are limitations on what should be variable name. A variable name must satisfy the following rules:
- A variable name must begin with a letter.
- A variable name maximum 31 characters length
- A variable name should not be keyword.
- A variable does not allow the white spaces and special symbols. But Underscore symbol is allowed.
- A variable is case sensitive. It means the variable declared in lower case the entire program followed the same case.
A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows:
Here, type must be a valid C data (pre defined or user defined). Variable list may consist of one or more identifier names separated by commas. Some valid declarations are shown here:
float avg, sal;
unsigned int marks;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
int d = 3, f = 5;
Variables can be declared in any of the following places:
Inside the function
In the definition of function as parameters.
Outside of all the functions.
These positions correspond to local variables, formal parameters and global variable respectively.
LValues and RValues
There are two kinds of expressions in C.
- lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
- rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals and constants are rvalues, so they not be assigned and cannot appear on the left-hand side. Following are valid statements:
int g = 20;
But following is not valid statements and would generate compile-time error: