< Previous | Contents | Next >

Declaring Variables

All right, now that youve got a basic understanding of types, its time to get back to the program. One of the first things I do is declare a variable (request that it be created) with the line:

int score;

In this code, I declare a variable of type int, which I name score. You use a variable name to access the variable. You can see that to declare a variable you specify its type followed by a name of your choosing. Because the declaration is a statement, it must end with a semicolon.

I declare three more variables of yet three more types in the next three lines. distance is a variable of type double. playAgain is a variable of type char. And shieldsUp is a variable of type bool.

Games (and all major applications) usually require lots of variables. Fortunately, Cþþ allows you to declare multiple variables of the same type in a single statement. Thats just what I do next in the line.

short lives, aliensKilled;

This line establishes two short variableslives and aliensKilled.

20 Chapter 1 n Types, Variables, and Standard I/O: Lost Fortune


Even though Ive defined a bunch of variables at the top of my main() function, you dont have to declare all of your variables in one place. As youll see later in the program, I often define a new variable just before I use it.