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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Do not use
constvariables for this! In the C language, aconstqualified 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:The proper solution is
#define. It’s probably best to use thelsuffix so that they’ll have typelong double, and include sufficiently many decimal places that the values will be correct forlong doubletypes 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.