Previous      Up      Previous     Course Home   e-mail

2 Assignment Statements

One of the most common statements (instructions) in C++ is the assignment statement, which has the form:

destination = expression;

= is the assignment operator. This statement means that the expression on the right hand side should be evaluated, and the resulting value stored at the desitnation named on the left. Most often this destination is a variable name, although in come cases the destination is itself arrived at by evaluating an expression to compute where we want to save the value.

Some examples of assignment statements would be


pi = 3.14159;
areaOfCircle = pi * r * r ;
circumferenceOfCircle = 2.0 * pi * r ;
Now, a few things worth noting:

When using variables on either side of an assignment, we need to declare the variables first:


double pi ;
double areaOfCircle ;
double circumferenceOfCircle ;
pi = 3.14159;
areaOfCircle = pi * r * r ;
circumferenceOfCircle = 2.0 * pi * r ;
Actually, we can combine the operations of declaring a varable and of assigning its first, or initial value:

double pi = 3.14159;
double areaOfCircle = pi * r * r ;
double circumferenceOfCircle = 2.0 * pi * r ;
Technically these are no longer assignments. Instead they are called initialization statements. But the effect is much the same.

I actually prefer this second, combined version, by the way.

Let me restate that. I strongly prefer that second version combining declarations with initialization.

One of the most common programming errors is declaring a variable, forgetting to assign it a value, but later trying to use it in a computation anyway. If the variable isn’t initialized, you basically get whatever bits happened to be left in memory by the last program that used that address. So you wind up taking an essentially random group of bits, feeding them as input to a calculation, feeding that result into another calculation, and so on, until eventually some poor schmuck gets a telephone bill for $1,245,834 or some piece of expensive computer-controlled machinery tears itself to pieces.

By getting into a habit of always initializing variables while declaring them, I avoid most of the opportunities for ever making this particular mistake.

 Previous      Up      Previous     Course Home   e-mail