Main Page | See live article | Alphabetical index

Magic number (programming)

In computer programming, a magic number is a special constant used for some specific purpose.

Magic numbers in UNIX files

An early convention in the UNIX operating system was that binary files started with two bytes containing a "magic number" identifying the type of the file. These were originally used by the UNIX linker and loader, but are now used by many other programs. In a wiggly hack, the very earliest magic numbers were PDP-11 branch instructions.

Magic numbers in code

Unnamed magic numbers in source code are bad programming practice because they make the program harder to read, understand, and maintain. 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. This is also important because a single number may have more than one meaning in a program. For example, the number '32' may be used to define a number of buffers used in a program, and also be chosen as the length of those buffers.

If there is a desire to change the length of the buffers, changing code that contains many code snippets such as

 for buf_index = 1 to 32
    for char_index = 1 to 32
       buffers[buf_index][char_index] = 0

requires the editor to check each use of the number to see which sense it is meant in, whereas if the code reads

 define NumberOfBuffers 32
 define BufferSize 32 

...

for buf_index = 1 to NumberOfBuffers for char_index = 1 to BufferSize buffers[buf_index][char_index] = 0

it is easy to change the buffer size throughout the program by editing just one line of code.

Macro languages and the C preprocessor were developed for just this purpose.