5C. Named Constants

A named constant is like a variable except that

  1. you are required to give an initial value for a named constant where you declare it, and

  2. you cannot change its value.

To declare a named constant, write const in front of its declaration. For example,

  const int height = 8;
declares a constant called height  with value 8. The program cannot change the value of height.


Why use named constants?

The number one difficulty with writing large computer programs is the amount of detail that needs to be exactly correct. Humans are not good at managing so much detail. But computers are great at keeping track of reams of detail. The obvious question is, can we get a computer to check our software and report errors or possible errors?

Compilers do exactly that. But in some ways, the programmer needs to tell the compiler what he or she is thinking so that it can detect departures from that. Named constants are an example. By saying that "variable" height  is a constant, you are telling the compiler that you do not want to change the value of height. If you make a mistake and try to change height , the compiler tells you about it.

Strings constants have type const char*

There are other reasons for using const. A string constant has type const char*. (It is, after all, a string constant.) If you want to give a name to a string constant, you are required to use const, as in:

  const char* myFavoriteFruit = "apple";


Exercises

  1. What is motivation for creating a constant rather than a variable? Answer