Use const
Instead of #define
to Define Constants
Symbolic constants make code more readable and maintainable. The constant’s name indicates its meaning, and if you need to change the value, you just have to change the value once, in the definition, and then recompile. C uses the preprocessor to create symbolic names for a constant:
#define MAX_LENGTH 100
The preprocessor then does a text substitution in your source code, replacing occurrences of MAX_LENGTH
with 100
prior to compilation.
The C++ approach is to apply the const
modifier to a variable declaration:
const int MAX_LENGTH = 100;
This treats MAX_LENGTH
as a read-only int
.
There are several advantages to using the const
approach. First, the declaration explicitly names the type. With ...
Get C++ Primer Plus 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.