One of the most common statements (instructions) in C++ is the assignment statement, which has the form:
destination = expression; |
Some examples of assignment statements would be
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 ;
double pi = 3.14159;
double areaOfCircle = pi * r * r ;
double circumferenceOfCircle = 2.0 * pi * r ;
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.