First Steps in Programming - Naming Variables
(Page 3 of 13 )
The name that you give to a variable, conveniently referred to as a variable name, can be defined with some flexibility. A variable name is a string of one or more letters, digits, and underscore characters (_) that begins with a letter (incidentally, the underscore character counts as a letter). Examples of good variable names are as follows:
Radius
diameter
Auntie_May
Knotted_Wool
D666
Because a name can’t begin with a digit, 8_Ball and 6_pack aren’t legal names. A variable name can’t include any other characters besides letters, underscores, and digits, so Hash! and Mary-Lou aren’t allowed as names. This last example is a common mistake, but Mary_Lou would be quite acceptable. Because spaces aren’t allowed in a name, Mary Lou would be interpreted as two variable names, Mary and Lou. Variables starting with one or two underscore characters are often used in the header files, so don’t use the underscore as the first letter when naming your variables; otherwise, you run the risk of your name clashing with the name of a variable used in the standard library. For example, names such as_this and_that are best avoided.
Although you can call variables whatever you want within the preceding constraints, it’s worth calling them something that gives you a clue to what they contain. Assigning the name x to a variable that stores a salary isn’t very helpful. It would be far better to call it salary and leave no one in any doubt as to what it is.
CAUTION The number of characters that you can have in a variable name will depend upon your compiler. Up to 31 characters are generally supported, so you can always use names up to this length without any problems. I suggest that you don’t make your variable names longer than this anyway, as they become cumbersome and make the code harder to follow. Some compilers will just truncate names that are too long.
Another very important point to remember when naming your variables is that C is case sensitive, which means that the names Democrat and democrat are completely different. You can demonstrate this by changing the printf() statement so that one of the variable names starts with a capital letter, as follows:
/* Program 2.3 Using more variables */
#include <stdio.h>
void main()
{
int brothers; /* Declare a variable called
brothers */
int brides; /* and a variable called brides
*/
brothers = 7; /* Store 7 in the variable
brothers */
brides = 7; /* Store 7 in the variable
brides */
/* Display some output */
printf("%d brides for %d brothers", Brides, brothers);
}
You’ll get an error message when you try to compile this version of the program. The compiler interprets the two variable names brides and Brides as different, so it doesn’t understand what Brides refers to. This is a common error. As I’ve said before, punctuation and spelling mistakes are one of the main causes of trivial errors.
Using Variables You now know how to name and declare your variables, but so far this hasn’t been much more useful than anything you learned in Chapter 1. Let’s try another program in which you’ll use the values in the variables before you produce the output.
Try It Out: Doing a Simple Calculation
This program does a simple calculation using the values of the variables:
/* Program 2.4 Simple calculations */
#include <stdio.h>
void main()
{
int Total_Pets; /* The total number of pets */
int Cats; /* The number of cats as pets */
int Dogs; /* The number of dogs as pets */
int Ponies; /* The number of ponies as pets
*/
int Others; /* The number of other pets */
/* Set the number of each kind of pet */
Cats = 2;
Dogs = 1;
Ponies = 1;
Others = 46;
/* Calculate the total number of pets */
Total_Pets = Cats + Dogs + Ponies + Others;
printf("We have %d pets in total", Total_Pets); /*
Output the result */
}
This example produces the output
=======================================================
We have 50 pets in total =======================================================
HOW IT WORKS
As in the previous examples, all the statements between the braces are indented by the same amount. This makes it clear that all these statements belong together. You should always organize your programs the way you see here: indent a group of statements that lie between an opening and closing brace by the same amount. It makes your programs much easier to read.
You first define five variables of type int:
int Total_Pets; /* The total number of pets */
int Cats; /* The number of cats as pets */
int Dogs; /* The number of dogs as pets */
int Ponies; /* The number of ponies as pets */
int Others; /* The number of other pets */
Because each of these variables will be used to store a count of a number of animals, it’s definitely going to be a whole number. As you can see, they’re all declared as type int.
Note that you could have declared all five variables in a single statement and included the comments, as follows:
int Total_Pets, /* The total number of pets */
Cats, /* The number of cats as pets */
Dogs, /* The number of dogs as pets */
Ponies, /* The number of ponies as pets */
Others; /* The number of other pets */
The statement is spread over several lines so that you can add the comments in an orderly fashion. Notice that there are commas separating each of the variable names. Because the comments are ignored by the compiler, this is exactly the same as the following statement:
int Total_Pets, Cats, Dogs, Ponies, Others;
You can spread C statements over as many lines as you want. The semicolon determines the end of the statement, not the end of the line.
Now back to the program. The variables are given specific values in these four assignment statements:
Cats = 2;
Dogs = 1;
Ponies = 1;
Others = 46;
At this point the variable Total_Pets doesn’t have an explicit value set. It will get its value as a result of the calculation using the other variables:
Total_Pets = Cats + Dogs + Ponies + Others;
In this arithmetic statement, you calculate the sum of all your pets on the right of the assignment operator by adding the values of each of the variables together. This total value is then stored in the variable Total_Pets that appears on the left of the assignment operator. The new value replaces any old value that was stored in the variable Total_Pets.
The printf() statement shows the result of the calculation by displaying the value of Total_Pets:
printf("We have %d pets in total", Total_Pets);
Try changing the numbers of some of the types of animals, or maybe add some more of your own. Remember to declare them, initialize their value, and include them in the Total_Pets statement.
Initializing Variables
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 variable Cats using this statement:
Cats = 2;
This sets the value of the variable Cats to 2.
So what was the value before this statement was executed? Well, it could be anything. The first statement creates the variable called Cats, 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 variable Cats as type int and 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 Statements 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.
This article is excerpted from Beginning C by Ivor Horton (Apress, 2004; ISBN 1590592530). Check it out at your favorite bookstore today. Buy this book now. |
Next: Basic Arithmetic Operations >>
More Code Examples Articles
More By Apress Publishing