Variable Declaration

  1. Variables used in a program must be declared before they can be used

  2. The syntax for variable declaration is:

    Type_Name Variable_Name_1, Variable_Name_2,  . . .   ;

    Example:

    int count, number_of_students, examScore;
    double height;

    Examples of Type-Names are:

    int - for integers
    float - for numbers having a fractional part and 7 digit precision
    double - for numbers having a fractional part and 15 digit precision
    char - for single characters such as letters, digits, and punctuation marks
    bool - for logical variables having only 2 values: true or false

  3. There are 2 acceptable styles for declaring variables:

    • A variable can be declared just before it is used for the first time. The type of the variable is then immediately known.
    • All variables used in a program are declared at the beginning of the main part of the program (our prefer choice here). It is then clear where one can look up the type of any identifier used in the program.

      Example:
      int main ( )
      {
      int number_of_dependents;
      double income, tax_rate;
      ...
      }