Tuesday, 3 July 2012

Declaration Of Variables


After designing suitable variable names, we must declare them to the compiler. Declaration does two things:
I. It tells the compiler what the \ ariable name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
Primary Type Declaration
A variable can be used to store a value of any data type. That is, the name has nothing to do with its type. The syntax for declaring a variable is as follows:
data-type vl,v2,....vn
vl, v2, ....vn are the names of variables. Variables are separated by commas. A declaration statement must end with a semicolon. For example, valid declarations are:
int count ;
int number, total;
double ratio;
int and double are the keywords to represent integer type and real type data values respectively. Table  shows various data types and their keyword equivalents.




The program segment given in Fig.  illustrates declaration of variables. main() is the beginning of the program. The opening brace signals the execution of the program. Declaration of variables is usually done immediately after the opening brace of the program. The variables can also be declared outside (either before or after) the main function. The importance of place of declaration will be dealt in detail later while discussing functions.

When an adjective (qualifier) short, long, or unsigned is used without a basic data type specifier. C compilers treat the data type as an int. If we want to declare a character variable as unsigned. then we must do so using both the terms like unsigned char.


User-Defined Type Declaration
C supports a feature known as "type definition" that allows users to define an identifier that would represent an existing data type. The user-defined data type identifier can later be used to declare variables . It takes the general form:
typedef type identifier;

Where type refers to an existing data type and "identifier" refers to the "new" name given to the data type. The existing data type may belong to any class of type, including the user-defined ones. Remember that the new type is 'new' only in name, but not the data type. typedef cannot create a new type. Some examples of type definition are:
typedef int units; typedef float marks;

Here, units symbolizes int and marks symbolizes float. They can be later used to declare vari­ables as follows:
units batchl, batch2;
marks namel[50], name2[50];

batch' and batch2 are inclared as int variable and name I [501 and name2[50] are declared as 50 element floating point array variables. The main advantage of typedef is that we can create meaning­ful data type names for increasing the readability of the program.