1. Summary:
Programming is not a magic number, so don't be a trick: avoid using literal constants such as 42 and 3.14159 in your code. They do not provide any description in themselves and make maintenance more complex because of the increased duplication that is difficult to detect. You can replace them with symbolic names and expressions, such as width * aspectratio.
2. Discussion:
Names can add information and provide a single point of maintenance, while the original data that repeats everywhere in the program is nameless and cumbersome to maintain. A constant should be an enumerator or a const value, with the appropriate scope and name.
There are often cases where this 42 may not be 42. To make things worse, if the programmer does some mental arithmetic (for example, "this 84 is obtained by 42 times 2 in front of the 5 lines of code"), then replacing the 42 with the other constants will become tedious and error-prone.
You should replace the directly-written dead string with a symbolic constant. Separating strings from code (such as putting strings into a dedicated. cpp file or resource file) allows non-programmers to review and update them, reduce duplication, and contribute to internationalization.
3. Example:
Example 1 important domain-specific constants should be placed at the namespace level.
Const 8192 sizeof(int * char_bit;
Example 2 class-specific constants. You can define static integer constants in the class definition, and other types of constants require a separate definition or a short function.
//file Widget.hclasswidget{Static Const intDefaultWidth = - //the value provided in the Declaration Static Const DoubleDefaultpercent;//values provided in the definition Static Const Char* Name () {return "Widgets";}};//file Widget.cppConst DoubleWidget::d efaultpercent =66.67;//values provided in the definitionConst intWidget::d efaultwidth;//The definition that is required
(c + + programming specification 17th) Avoid using "magic number"