I am reading the book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices, and it says that using #define
is bad to use. When I was looking at some of the header files they have many #define
s. If it's bad to use #define
s, why is there so many? Thank you.
#define
are a bad practice because:
They don't have any Scope:
#define
s don't respect scopes so there is no way to create a class scoped namespace. While variables can be scoped in classes.
Weird magical numbers during compilation errors:
If you are using #define
those are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.
Debugging Problems:
Also for same reasons mentioned in #2, while debugging #define
won't provide much of an help really.
Hence it is much better idea to use const
variables instead of a #define
.
They are superior to #define
in all above mentioned aspects.Only areas where #define
can be really helpful are where you need actual textual replacement in code or in defining include header guards.
Why are
#define
widely used in C standard header files?
One reason that comes to my mind is, In C(unlike C++) const
declarations do not produce constant expressions.Which means prior to introduction of Variable length arrays in C standard one cannot write something like:
const int max_val = 100;
int foos[max_val];
because in C max_val
is not a compile time constant, and prior to introduction of VLA's array subscripts were needed to be compile time constants.
So one had to write this instead as:
#define MAX_VAL 100
int foos[MAX_VAL];
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