First Steps in (C) Programming, introduction - Initializing Variables
(Page 6 of 8 )
In the previous example, you declared each variable with a statement such as this:
int Cats; /* The number of cats as pets */
You set the value of the variableCatsusing this statement:
Cats = 2;
This sets the value of the variableCatsto 2.
So what was the value before this statement was executed? Well, it could be anything. The first statement creates the variable calledCats, but its value will be whatever was left in memory from the last program that used this bit of memory. The assignment statement that appeared later set the value to 2, but it would be much better to initialize the variable when you declare it. You can do this with the following statement:
int Cats = 2; /* The number of cats as pets */
This statement declares the variableCatsas typeintand sets its initial value to 2.
Initializing variables as you declare them is a very good idea in general. It avoids any doubt about what the initial values are, and if the program doesn’t work as it should, it can help you track down the errors. Avoiding leaving spurious values for variables when you create them also reduces the chances of your computer crashing when things do go wrong. Inadvertently working with junk values can cause all kinds of problems. From now on, you’ll always initialize variables in the examples, even if it’s just to 0.
Arithmetic StatementsThe previous program was the first one that really did something. It was very simple—just adding a few numbers—but it was a significant step forward. This was an elementary example of using an arithmetic statement to perform a calculation. Now let’s look at some more sophisticated calculations that you can do.
Next: Basic Arithmetic Operations >>
More C++ Articles
More By Apress Publishing
|
This article is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530). Check it out today at your favorite bookstore. Buy this book now.
|
|