I'm wondering what would be the best way to store math constants that are used throughout an entire program?
#define PI 3.14159265
#define SPEEDOFLIGHT 2.99792458e8
or
enum constants { PI = 3.14159265; SPEEDOFLIGHT = 2.99792458e8; }
Thanks
I'm wondering what would be the best way to store math constants that are used throughout an entire program?
#define PI 3.14159265
#define SPEEDOFLIGHT 2.99792458e8
or
enum constants { PI = 3.14159265; SPEEDOFLIGHT = 2.99792458e8; }
Thanks
None of them, use constant values to preserve compiler's type checking:
static const double PI = 3.14159265;
static const double SPEEDOFLIGHT = 2.99792458e8;
#define
is text replacement only and type unaware.double
values.EDIT: thanks aaa
. I forgot the static
keyword, specially useful when the constants are declared in c headers. (In C++ the static is not needed)
Since enum's are integer constants, I would go with #define
.
I agree with jdehaan that global const
objects are even better.
Agree with jdehaan, prefer constants to do more explicit type checking/conversion.
In addition, using an enum like you described isn't really the purpose of an enum. Those constants are only mathematically related (if cosmologist hocus-pocus ends up being correct). The purpose of an enum is to combine like values, such as:
enum color
{
red = 0xFF0000;
yellow = 0xFFFF00;
baby_puke_green = 0x9ACD32;
}
Personally i prefer to just make pi and c = 1 and let the universe deal with the problem
Do not use const
variables for this! In the C language, a const
qualified variable is not a constant in the sense of constant expression, so it cannot be used in initializing a static/global variable. This has major practical consequences; for instance, the following will not work:
static const double powers_of_pi[] = { 1, PI, PI*PI, PI*PI*PI, PI*PI*PI*PI, };
The proper solution is #define
. It's probably best to use the l
suffix so that they'll have type long double
, and include sufficiently many decimal places that the values will be correct for long double
types up to 128-bit. Then you can use them wherever any floating point type is expected; C will silently convert them down to lower precision as needed.