Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Constants

Like variables, constants are data storage locations. But variables can vary; constants, on the other hand and as you might have guessed, do not vary.

You must initialize a constant when you create it, and you cannot assign a new value later; after a constant is initialized, its value is, in a word, constant.

Literal Constants

C++ has two types of constants: literal and symbolic.

A literal constant is a value typed directly into your program wherever it is needed. For example:

int myAge = 39;

myAge is a variable, of type int; 39 is a literal constant. You can't assign a value to 39, and its value can't be changed.

Symbolic Constants

A symbolic constant is a constant that is represented by a name, just as a variable is. Unlike a variable, however, after a constant is initialized, its value can't be changed. If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew there were 15 students per class:

students = classes * 15;

NOTE

* indicates multiplication.

In this example, 15 is a literal constant. Your code would be easier to read and easier to maintain if you substituted a symbolic constant for this value:

students = classes * studentsPerClass

If you later decided to change the number of students in each class, you could do so where you define the constant studentsPerClass without having to make a change every place you used that value.

Defining Constants with #define

To define a constant the old-fashioned, evil, politically incorrect way, you would enter:

#define studentsPerClass 15

Note that studentsPerClass is of no particular type (int, char, and so on). #define does a simple text substitution. Every time the preprocessor sees the word studentsPerClass, it puts 15 in the text.

Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15.

Defining Constants with const

Although #define works, there is a better, less fattening, and more tasteful way to define constants in C++:

const unsigned short int studentsPerClass = 15;

This example also declares a symbolic constant named studentsPerClass, but this time studentsPerClass is typed as an unsigned short int.

This takes longer to type, but offers several advantages. The biggest difference is that this constant has a type, and the compiler can enforce that it is used according to its type.

  • + Share This
  • 🔖 Save To Your Account