Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Variables and Constants 47

3


Defining a Variable ................................................................................................


Up to this point, you have seen a number of variables created and used. Now, it is time to
learn how to create your own.
You create or definea variable by stating its type, followed by one or more spaces, fol-
lowed by the variable name and a semicolon. The variable name can be virtually any
combination of letters, but it cannot contain spaces. Legal variable names include x,
J23qrsnf, and myAge. Good variable names tell you what the variables are for; using
good names makes it easier to understand the flow of your program. The following state-
ment defines an integer variable called myAge:
int myAge;

apply to your compiler. If your output from Listing 3.1 was different, you
should consult your compiler’s manual for the values that your variable
types can hold.

When you declare a variable, memory is allocated (set aside) for that vari-
able. The valueof the variable will be whatever happened to be in that
memory at that time. You will see in a moment how to assign a new value
to that memory.

NOTE


As a general programming practice, avoid such horrific names as J23qrsnf, and restrict
single-letter variable names (such as xor i) to variables that are used only very briefly.
Try to use expressive names such as myAgeor howMany. Such names are easier to under-
stand three weeks later when you are scratching your head trying to figure out what you
meant when you wrote that line of code.
Try this experiment: Guess what these programs do, based on the first few lines of code:
Example 1
int main()
{
unsigned short x;
unsigned short y;
unsigned short z;
z = x * y;
return 0;
}
Free download pdf