I l@ve RuBoard Previous Section Next Section

4.5 Variable Declarations

Before you can use a variable in C++, it must be defined in a declaration statement. A variable cannot be used unless it is declared.

A variable declaration serves three purposes:

  • It defines the name of the variable.

  • It defines the type of the variable (integer, real, character, etc.).

  • It gives the programmer a description of the variable.

The declaration of a variable answer can be:

int answer;     // the result of our expression

The keyword int tells C++ that this variable contains an integer value. (Integers are defined below.) The variable name is answer. The semicolon is used to indicate the statement end, and the comment is used to define this variable for the programmer.

The general form of a variable declaration is:

type  name;   // comment 

Type is one of the C++ variable types (int, float, etc.) Name is any valid variable name. The comment explains what the variable is and what it will be used for. Variable declarations come just before the main( ) line at the top of a program. (In Chapter 9 you will see how local variables may be declared elsewhere.)

    I l@ve RuBoard Previous Section Next Section