ArticleslgStudy

mathematics

Magic number (programming)

Magic number (programming) is a mathematics topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Magic number (programming) rather than just read about it. In short: 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 (see list of file signatures).

Key takeaways

  • Magic number (programming) belongs to mathematics; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Magic number (programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Magic number (programming) from memory before moving on to harder problems.

Reference excerpt

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 (see list of file signatures). 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 constexpr int SIXTEEN = 16;, while constexpr 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 testUserName might be better than using the literal "John" directly.

Example For example, if it is required to randomly shuffle the values in an array representing a standard pack of playing cards, this pseudocode does the job using the Fisher–Yates shuffle algorithm:

for i from 1 to 52 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:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Magic number (programming)

Start with the simplest possible case. Write down what Magic number (programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In mathematics, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Magic number (programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Magic number (programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Magic number (programming)

In research
Magic number (programming) appears in mathematics research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Magic number (programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Magic number (programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics Anti-patterns, Computer programming folklore, Debugging, so understanding it makes those chapters shorter.
In everyday life
Look for Magic number (programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Magic number (programming)” →

How to study Magic number (programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Magic number (programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Magic number (programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Magic number (programming) in simple terms?

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 iden…

Why does Magic number (programming) matter?

Because it connects several mathematics ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Magic number (programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Magic number (programming).

Tags

  • Anti-patterns
  • Computer programming folklore
  • Debugging
  • Software engineering folklore

Keep exploring