Magic number (programming)
Appearance
In computer programming, a magic number is a special constant used for some specific purpose.
This article is a stub. You can help Wikipedia by fixing it.
Unnamed magic numbers are bad programming practice because:
- they make the program harder to read. For example, if the below pseudocode snippet is supposed to iterate through the months of the year
- for n = 1 to 12
- is more difficult to elucidate the meaning of than
- for n = 1 to MonthsPerYear
- they make changing the value of the magic number globally throughout the code much more difficult. If the magic number is named beforehand, the definition need merely be changed to affect the rest of the named constants. For example,
- for n = 1 to 12
- print "There are " 12-n " more months to go"
- print "This is month " n " of " 12
- each 12 must be changed if we wish to use a different calendar, for example. However, if we say
- define MonthsPerYear = 12
- for n = 1 to MonthsPerYear
- print "There are " MonthsPerYear-n " more months to go"
- print "This is month " n " of " MonthsPerYear
- When we wish to change the constant, we merely change its definition.