Constants: const and enum
It is very useful to define symbolic constants. The following example calculates the areas of circles, and so PI is defined as a constant:
NOTE
Constants are commonly written in uppercase so that it's easy to identify them in code.
;> double PI = 3.14; ;> double r = 2.3; ;> PI*r*r; (double) 16.6106
Using const Declarations
Even though it is a constant, it is possible to assign values to PI, which seems to contradict the idea of a constant. (One of Murphy's Laws for software development is “Variables won't and constants aren't.”) One C++ solution is the const modifier. When applied to a type in a declaration, it flags the declared symbol as not being modifiable:
;> const double PI = 3.14; ;> PI = 3; CON 3: Cannot ...
Get C++ By Example: UnderC Learning Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.