Constants


Any well-written program has constants that are used throughout it. Say you were managing an enchilada packaging company, and you were always putting the weight into different parts of the program. By placing it at the top of the code as a constant, an unchangeable variable, you would only have to change the one constant if your enchiladas started weighing more.

In Pascal, there was a section at the beginning of each file named const where all constants had to be declared. C++ is a lot more flexible than Pascal was; there's no special section where your constants have to go. If you want them to be global (that is, usable by everything), you have to put them outside of a function. The best place is probably the very top of a program.

Constants are declared just like you're declaring a regular variable and initializing it to a value, but you add the const keyword in front of it. For instance, to make a constant with the value 14, you say:

const int taco = 14; /* Create a constant named taco with the value 14 */

Note that you have to put the type of variable it is in addition to a name and value. This may feel a little wierd; it's better to think of these constants as variables you aren't allowed to change rather than constants. Let's try using constants in a program:

const int taco = 14;
const int burrito = 15;

void main(void)
{
   int chimichanga;

   chimichanga = taco;

   if (chimichanga > 10)
     chimichanga = 1;
   else
     chimichanga = 5;

   chimichanga = chimichanga + burrito;
 
   if (burrito > taco)
     chimichanga = 400;
}

Notice how we're able to use taco and burrito all throughout the program. We can't, however, give them a new value, because of the const keyword in front of them. If, for some reason, we needed to change taco to 50, it would just mean changing one place at the top, saving potential programming energy for other tasks.


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises