4F. Constants

Constants

A constant is a "variable" that you cannot change. To declare a constant, write const in front of the type. For example,

  const int nine = 9;
  const int size = 200;
  const double pi = 3.1415926536;


Why use constants?

Computer programs are necessarily detailed, and the details need to be right. Because of that, computer programmers make mistakes, and those mistakes have, over time, cost billions of dollars.

One way to reduce mistakes is to let the computer check your programs for you. It can't check everything, but any checking that it can do is valuable.

You can reduce your mistakes by taking away opportunities to make mistakes. Constants are one way of doing that. If you do not want to change something, mark it as a constant so that you cannot accidentally change it.



Exercises

  1. Why would you want to put restrictions on yourself by making a variable constant? Isn't it better to have fewer restrictions so that you can do whatever you want to do? Answer

  2. How can you create a constant integer called maxNameSize whose value is 40? Answer