Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: enum VS #define for mathematical constants?

Tags:

c

math

constants

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

like image 443
Alex Marcotte Avatar asked Aug 07 '10 20:08

Alex Marcotte


People also ask

Which is better #define or enum in C?

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 .

Which is better #define or enum?

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.

When should we use enum in C?

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.

When to use enum VS define?

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!


1 Answers

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.

like image 86
R.. GitHub STOP HELPING ICE Avatar answered Sep 30 '22 09:09

R.. GitHub STOP HELPING ICE