Magic number (programming)
In computer programming, a magic number or magic constant is a numeric literal in source code whose meaning is unclear to the reader. The term is also used outside of programming to refer to a number whose meaning is not obvious without additional knowledge — for example, some file formats are identified by an embedded magic number in the file ). Also, a number that is relatively uniquely associated with a particular concept, such as a universally unique identifier, might be classified as a magic number.
In computer programming, a magic number or magic constant is a numeric literal in source code whose meaning is unclear to the reader. The term is also used outside of programming to refer to a number whose meaning is not obvious without additional knowledge — for example, some file formats are identified by an embedded magic number in the file ). Also, a number that is relatively uniquely associated with a particular concept, such as a universally unique identifier, might be classified as a magic number. ==Numeric literal== Using a magic number in source code is considered an anti-pattern and breaks one of the oldest rules of programming, dating back to the COBOL, FORTRAN and PL/1 manuals of the 1960s. For example, in the following code that computes a price after tax, 1.05 is a magic number since the value encodes the sales tax rate, 5%, in a way that is less than obvious. price_after_tax = 1.05 * price The use of magic numbers in code obscures the developers' intent in choosing that number, increases opportunities for subtle errors, and makes it more difficult for the program to be adapted and extended in the future. As an example, it is difficult to tell whether every digit in 3.14159265358979323846 is correctly typed, or if this constant for pi can be truncated to 3.14159 without affecting the functionality of the program with its reduced precision. Replacing all significant magic numbers with named constants (also called explanatory variables) makes programs easier to read, understand and maintain. The example above can be improved by adding a descriptively named variable: TAX = 0.05 price_after_tax = (1.0 + TAX) * price A good name can result in code that is more easily understood by a maintainer who is not the original author and even the original author after a period of time. An example of an uninformatively named constant is int SIXTEEN = 16 , while int NUMBER_OF_BITS = 16 might be more useful. Non-numeric data can have the same magical properties, and therefore, the same issues as magic numbers. Thus, declaring const string testUserName = "John" and using might be better than using the literal "John" directly. j := i + randomInt(53 - i) - 1 a.swapEntries(i, j) where a is an array object, the function randomInt(x) chooses a random integer between 1 and x, inclusive, and swapEntries(i, j) swaps the ith and jth entries in the array. In the preceding example, 52 and 53 are magic numbers, also not clearly related to each other. It is considered better programming style to write the following: int deckSize:= 52 for i from 1 to deckSize j := i + randomInt(deckSize + 1 - i) - 1 a.swapEntries(i, j) This is preferable for several reasons: Better readability. A programmer reading the first example might wonder, What does the number 52 mean here? Why 52? The programmer might infer the meaning after reading the code carefully, but it is not obvious. Magic numbers become particularly confusing when the same number is used for different purposes in one section of code. Easier to maintain. It is easier to alter the value of the number, as it is not duplicated. Changing the value of a magic number is error-prone, because the same value is often used several times in different places within a program. Also, when two semantically distinct variables or numbers have the same value they may be accidentally both edited together. To modify the first example to shuffle a Tarot deck, which has 78 cards, a programmer might naively replace every instance of 52 in the program with 78. This would cause two problems. First, it would miss the value 53 on the second line of the example, which would cause the algorithm to fail in a subtle way. Second, it would likely replace the characters "52" everywhere, regardless of whether they refer to the deck size or to something else entirely, such as the number of weeks in a Gregorian calendar year, or more insidiously, are part of a number like "1523", all of which would introduce bugs. By contrast, changing the value of the deckSize variable in the second example would be a simple, one-line change. Encourages documentation. The single place where the named variable is declared makes a good place to document what the value means and why it has the value it does. Having the same value in a plethora of places either leads to duplicate comments (and attendant problems when updating some but missing some) or leaves no one place where it's both natural for the author to explain the value and likely the reader shall look for an explanation. Coalesces information. The declarations of "magic number" variables can be placed together, usually at the top of a function or file, facilitating their review and change. Detects typos. Using a variable (instead of a literal) takes advantage of a compiler's checking. Accidentally typing "62" instead of "52" would go undetected, whereas typing " dekSize " instead of " deckSize " would result in the compiler's warning that dekSize is undeclared. Reduces typing. If a IDE supports code completion, it will fill in most of the variable's name from the first few letters. Facilitates parameterization. For example, to generalize the above example into a procedure that shuffles a deck of any number of cards, it would be sufficient to turn deckSize into a parameter of that procedure, whereas the first example would require several changes. function shuffle (int deckSize) for i from 1 to deckSize j := i + randomInt(deckSize + 1 - i) - 1 a.swapEntries(i, j) Disadvantages are: Breaks locality. When the named constant is not defined near its use, it hurts the locality, and thus comprehensibility, of the code. Putting the 52 in a possibly distant place means that, to understand the workings of the "for" loop completely (for example to estimate the run-time of the loop), one must track down the definition and verify that it is the expected number. This is easy to avoid (by relocating the declaration) when the constant is only used in one portion of the code. When the named constant is used in disparate portions, on the other hand, the remote location is a clue to the reader that the same value appears in other places in the code, which may also be worth looking into. Causes verbosity. The declaration of the constant adds a line. When the constant's name is longer than the value's, particularly if several such constants appear in one line, it may make it necessary to split one logical statement of the code across several lines. An increase in verbosity may be justified when there is some likelihood of confusion about the constant, or when there is a likelihood the constant may need to be changed, such as reuse of a shuffling routine for other card games. It may equally be justified as an increase in expressiveness. Performance considerations. It may be slower to process the expression deckSize + 1 at run-time than the value "53". That being said, most modern compilers will use techniques like constant folding and loop optimization to resolve the addition during compilation, so there is usually no or negligible speed penalty compared to using magic numbers in code. Especially the cost of debugging and the time needed trying to understand non-explanatory code must be held against the tiny calculation cost. Use of 2 to check whether a number is even or odd, as in isEven = (x % 2 == 0) , where % is the modulo operator Use of simple literals, e.g., in expressions such as circumference = 2 * Math.PI * radius , or for calculating the discriminant of a quadratic equation as d = b^2 − 4*a*c Use of powers of 10 to convert metric values (e.g. between grams and kilograms) or to calculate percentage and per mille values Exponents in expressions such as (f(x) ** 2 + f(y) ** 2) ** 0.5 for \sqrt{f(x)^2 + f(y)^2} The literals 1 and 0 are sometimes used to represent the Boolean values true and false. Arguably, assigning these values to names such as TRUE and FALSE might be better. In C and C++, 0 is often used to mean null pointer even though the C standard library defines a macro NULL and modern C++ includes a keyword .
References
- ^ "PNG (Portable Network Graphics) Specification Version 1.0: 12.11. PNG file signature" . MIT . 1996-10-01. Archived from the original on 2023-03-26. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "The BIOS/MBR Boot Process" . NeoSmart Knowledgebase . 2015-01-25. Archived from the original on 2023-03-26 . Retrieved 2019-02-03 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1549148400.0
- ^ "TI E2E Community: Does anyone know if the following configurations can be done with MCP CLI Tool?" . Texas Instruments . 2011-08-27. Archived from the original on 2022-10-07. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ Newcomer, Joseph M. (2001-10-13). "Message Management: Guaranteeing uniqueness" . Developer Fusion . Archived from the original on 2005-04-21 . Retrieved 2007-11-16 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1195167600.0
- ^ Osterman, Larry (2005-07-21). "UUIDs are only unique if you generate them..." Larry Osterman's WebLog - Confessions of an Old Fogey . MSDN. Archived from the original on 2023-03-28 . Retrieved 2007-11-16 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1195167600.0
- ^ "RFC 9562 - Universally Unique IDentifiers (UUIDs)" . ietf.org . May 2024 . Retrieved 2024-08-09 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1723158000.0
- ^ "Deploying Java Applets With Family JRE Versions in Java Plug-in for Internet Explorer" . Oracle . Archived from the original on 2022-11-30 . Retrieved 2023-03-28 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1679958000.0
- ^ "GNU GRUB Installation, Section 3.4: BIOS installation" . Gnu.org . Archived from the original on 2023-03-15 . Retrieved 2014-06-26 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1403737200.0
- ^ Heddings, Lowell (2014-11-03). "Magic Numbers: The Secret Codes that Programmers Hide in Your PC" . How-To Geek . Archived from the original on 2023-03-26 . Retrieved 2017-10-03 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1506985200.0
- ^ Cavit, Doug (2012-04-24). "Guarding against re-use of stale object references" . Microsoft Secure . Archived from the original on 2018-07-26 . Retrieved 2018-07-26 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1532559600.0
- ^ Boleyn, Erich Stefan (1995-04-04). "Comments on the 'MultiBoot Standard' proposal" . Uruk.org . Archived from the original on 2023-03-26. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ McNamara, Paul (2012-07-19). "Microsoft code contains the phrase 'big boobs' ... Yes, really" . Network World . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ WebKit , The WebKit Open Source Project, 2023-01-06 , retrieved 2023-01-06 Wikipedia revision 1373193504, retrieved 2026-11-20 · 1672959600.0
- ^ "AddressSanitizer - FAQ" . GitHub . Retrieved 2022-05-18 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1652828400.0
- ^ "INTEL 80386 PROGRAMMER'S REFERENCE MANUAL" . MIT . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ Scheppner, Carolyn. "Amiga Mail Vol.2 Guide" . Cataclysm.cx . Archived from the original on 2011-07-18 . Retrieved 2010-08-20 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1282258800.0
- ^ Maguire, James (2008-12-09). "Bjarne Stroustrup on Educating Software Developers" . Datamation.com . Archived from the original on 2018-06-23. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "Bug Check 0xDEADDEAD MANUALLY_INITIATED_CRASH1" . Microsoft Documentation . 2023-06-19. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "Safari Version 14.0.1 Unexpectedly Quits" . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "Device Tree Specification" . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "strncat_s, _strncat_s_l, wcsncat_s, _wcsncat_s_l, _mbsncat_s, _mbsncat_s_l" . Microsoft Documentation . Retrieved 2019-01-16 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1547593200.0
- ^ Vogel, Jeff (2007-05-29). "Six ways to write more comprehensible code" . IBM Developer . Archived from the original on 2018-09-26. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ Personal communication with Dennis M. Ritchie. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ Martin, Robert C. (2009). "Chapter 17: Smells and Heuristics - G16 Obscured Intent". Clean Code - A handbook of agile software craftsmanship . Boston: Prentice Hall. p. 295 . ISBN 978-0-13-235088-4 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ a b c Martin, Robert C. (2009). "Chapter 17: Smells and Heuristics - G25 Replace Magic Numbers with Named Constants". Clean Code - A handbook of agile software craftsmanship . Boston: Prentice Hall. p. 300 . ISBN 978-0-13-235088-4 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ a b c Paul, Matthias R. (2002-04-03). "[fd-dev] Ctrl+Alt+Del" . freedos-dev . Archived from the original on 2017-05-10 . Retrieved 2017-09-09 . (NB. Mentions a number of magic values used by IBM PC -compatible BIOSes (0000h, 1234h), DOS memory managers like EMM386 (1234h) and disk caches like SMARTDRV (EBABh, BABEh) and NWCACHE (0EDCh, EBABh, 6756h).) Wikipedia revision 1373193504, retrieved 2026-11-20 · 1504911600.0
- ^ a b c d e f Paul, Matthias R. (2002-04-09). "[fd-dev] CuteMouse 2.0 alpha 1" . freedos-dev . Archived from the original on 2022-04-07 . Retrieved 2022-08-04 . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1659567600.0
- ^ "The Unix Tree V6/usr/sys/ken/sys1.c" . The Unix Heritage Society . Archived from the original on 2023-03-26. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "The Unix Tree V7/usr/sys/sys/sys1.c" . The Unix Heritage Society . Archived from the original on 2023-03-26. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ a b c d e f Birkett, Andrew. "Win32 Debug CRT Heap Internals" . Nobugs.org . Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ a b c d e f "Technical Note TN2151: Understanding and Analyzing Application Crash Reports" . Apple Developer Documentation . 2009-01-29. Archived from the original on 2018-12-13. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ "Odd Comments and Strange Doings in Unix" . Bell Labs . 2002-06-22. Archived from the original on 2006-11-04. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
- ^ Chen, Raymond (2008-03-24). "What's the difference between the COM and EXE extensions?" . The Old New Thing . Archived from the original on 2019-02-18. Wikipedia revision 1373193504, retrieved 2026-11-20 · 1795129200.0
Cite this
"Magic number (programming)". 1788523672. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1373193504 JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy