I l@ve RuBoard Previous Section Next Section

4.7 Assignment Statements

Variables are given a value through the use of assignment statements. Before a variable can be used, it must be declared. For example:

int answer;    // Result of a simple computation

The variable may then be used in an assignment statement, such as:

answer = (1 + 2) * 4; 

The variable answer on the left side of the equal sign (=) is assigned the value of the expression (1 + 2) * 4 on the right side. The semicolon ends the statement.

When you declare a variable, C++ allocates storage for the variable and puts an unknown value inside it. You can think of the declaration as creating a box to hold the data. When it starts out, it is a mystery box containing an unknown quantity. This is illustrated in Figure 4-1A. The assignment statement computes the value of the expression and drops that value into the box, as shown in Figure 4-1B.

Figure 4-1. Declaration and assignment statements
figs/C++2_0401.gif

The general form of the assignment statement is:

variable = expression; 

The equal sign (=) is used for assignment, not equality.

In Example 4-2, the variable term is used to store an integer value that is used in two later expressions. Variables, like expressions, can be output using the output operator <<, so we use this operator to check the results.

Example 4-2. tterm/tterm.cpp
#include <iostream>

int term;       // term used in two expressions
int main(  )
{

    term = 3 * 5;
    std::cout << "Twice " << term << " is " << 2*term << "\n";
    std::cout << "Three times " << term << " is " << 3*term << "\n";
    return (0);
}
    I l@ve RuBoard Previous Section Next Section