If you're a beginning programmer and want to get more deeply into programming with variables, you've come to the right place. This article, the first of three parts, is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530).
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.
The 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.