This question already has an answer here:
- “static const” vs “#define” vs “enum” 17 answers
In many programs a #define
serves the same purpose as a constant. For example.
#define FIELD_WIDTH 10
const int fieldWidth = 10;
I commonly see the first form preferred over the other, relying on the pre-processor to handle what is basically an application decision. Is there a reason for this tradition?
The reason is that most of the time, you want a constant, not a
const
-qualified variable. The two are not remotely the same in the C language. For example, variables are not valid as part of initializers forstatic
-storage-duration objects, as non-vla array dimensions (for example the size of an array in a structure, or any array pre-C99).There is a very solid reason for this:
const
in C does not mean something is constant. It just means a variable is read-only.In places where the compiler requires a true constant (such as for array sizes for non-VLA arrays), using a
const
variable, such asfieldWidth
is just not possible.Although a const int will not always be appropriate, an enum will usually work as a substitute for the #define if you are defining something to be an integral value. This is actually my preference in such a case.
In C++ this is a huge advantage as you can scope your enum in a class or namespace, whereas you cannot scope a #define.
In C you don't have namespaces and cannot scope an enum inside a struct, and am not even sure you get the type-safety, so I cannot actually see any major advantage, although maybe some C programmer there will point it out to me.