< Previous | Contents | Next >

Using Constants

I define a constant, ALIEN_POINTS, to represent the point value of an alien.

const int ALIEN_POINTS = 150;

I simply use the keyword const to modify the definition. Now I can use ALIEN_POINTS just like any integer literal. Also, notice that the name I chose for the constant is in all capital letters. This is just a convention, but its a common one. An identifier in all caps tells a programmer that it represents a constant value.

Next I put the constant to use in the following line:

int score = aliensKilled * ALIEN_POINTS;

I calculate a players score by multiplying the number of aliens killed by the point value of an alien. Using a constant here makes the line of code quite clear.


Tra p

image

You can’t assign a new value to a constant. If you try, you’ll generate a compile error.

image