17. Avoid magic numbers

Summary

Programming isn’t magic, so don’t incant it: Avoid spelling literal constants like 42 or 3.14159 in code. They are not self-explanatory and complicate maintenance by adding a hard-to-detect form of duplication. Use symbolic names and expressions instead, such as width * aspectRatio.

Discussion

Names add information and introduce a single point of maintenance; raw numbers duplicated throughout a program are anonymous and a maintenance hassle. Constants should be enumerators or const values, scoped and named appropriately.

One 42 may not be the same as another 42. Worse, “in-head” computations made by the programmer (e.g., “this 84 comes from doubling the 42 used five lines ago”) make it tedious and error-prone ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices 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.