Initializing Variables

  1. A variable can be given a value when it is declared. This is called initializing the variable.

  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.1415926535897932;

    Note that the identifier inch2cm above should also 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.

  8. Constants can be initialized before "int main( )" but after "using namespace std". They are then global constants (available to the remaining parts of the program).

  9. Note that although global variables are allowed in C++, you are not allowed to them here in this course at all! Using global variables is an extremely bad programming habit. On our exams, you will very likely have a large fraction of the points taken off!