C++ symbolic constants with const

const int candidates=3;
const float standard_deduction=2000;
const float PI=3.141592;
const string inputerror_message="Error input. Please re-enter: ";

"constant variable" A variable, but its value can't vary.
Once initialized at declaration, syntax error to try to change later.
Use for values that are relatively stable for the life of the program.

circumference = 2 * PI * radius;
cout << standard_deduction * exemptions;
if (num_names != candidates)
  cout << inputerror_messgae;
Readability (no "magic numbers" in the program).

Maintainability. If number of candidates changes, say to 2, only need to change the definition of candidates in the const statement, not have to search all over the program for the 3's that mean number of candidates.

Especially used for array sizes.

Typically are global (declared outside of any function). Available to all following code.

#includes
...
consts
...
prototypes
...
main()
...
other functions
...


Next (arrays)


©David Wills