Search code examples
c++constantsstandardsmagic-numbers

Is there a standard way to define a big list of "magic numbers" or parameters?


Abstractly, say you were building a physics simulation and needed many universal constants or typical values for things like mass. It feels like there should be a standard approach to implementing this? I'm mainly a hobbiest, using C++, and I can think of ways it can be done but unsure what should be done, and I'm worried I'd hit some messy pitfall.

So if you had constants like g, G, pi, alpha, e, h, h-bar etc and lots of values like "Typical Star: Mass = 1 MSolar, wavelength = 600nm" and so on. how would you implement them and potentially group and organise them in a way thats efficient?

I was considering just a header file with the values as either #define macros, or consts, maybe even a std::map, but that feels like adding a lot of global variables in a way that would quickly get out of hand. Is it just something to endure or are there cleaner ways?


Solution

  • The C++ way of doing this is to have them as inline constexpr variables in a header file. That's what the standard does with some constants. You can define yours:

    namespace Constants {
    inline constexpr auto goldenRatio = 1.61803398875;
    // ...
    };