Search code examples
c++pythoncmagic-numbersconcept

Does the concept of "magic number" change from language to language?


Take the following code in C/C++, for example:

int foo[] = {0, 0, 0, 0};

No magic numbers, right?
Now, the Python "equivalent" of that would be:

foo = [0, 0, 0, 0]

Still no magic numbers.
However, in Python, that same thing can be written like this:

foo = [0] * 4

And now we DO have a magic number. Or do we?
I'm guessing this and other similar things are present on these and other languages.


Solution

  • Not every number is a magic constant. The reason 4 and the four 0 are magic numbers (in any language) is that it's entirely unclear why that number is 4 and not any other number.

    For example in the context of a game that is played with the well known six-sided die

    def roll_die():
        return random.randint(1,6)
    

    this code has no magic numbers, because it's very easy to see where the numbers came from.

    On the other hand it can be hard to guess which numbers other programmers know. For example, not everyone might know the number of cards in a deck, so it makes more sense to use a named constant there.

    It entirely depends on the context if a number is "magic" or not, it has nothing to do with the language. When in doubt, name your constants just to be on the safe side.