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
In C, enum is preferable only when we are working with natural group of constants. In all other cases it is #define and only #define .
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. Hereby mistake, the state of wed is 2, it should be 3.
One of the differences between the two is that #define is a pre-processor directive while enum is part of the actual C language. #define statements are processed by the compiler before the first line of C code is even looked at!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With