Initializing Variables

  1. A variable can be given a value when it is declared.

  2. For example:
    double inch2cm = 2.54, length_in_cm, length_in_inch = 6.721;

  3. Technically speaking these are not considered as assignment statements.

  4. Alternately we can write:
    double inch2cm(2.54), length_in_cm, length_in_inch(6.721);

  5. Make sure that a variable has a meaningful value before it is used.

  6. Identifiers whose values should not be altered in the program should be declared as constants using the key word const. They must be initialized during declaration. For example, the identifier that stores the value of pi:

    const double pi = 3.14159265;

    Note that the identifier inch2cm should really be made a constant.

  7. Any attempt to change the value of a constant identifier in the program will cause a compilation error. This feature helps to ensure that programmers cannot accidentally alter the values of constants.