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 #defines. If it’s bad to use #defines, why is there so many? Thank you.
I am reading the book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices,
Share
#defineare a bad practice because:#defines don’t respect scopes so there is no way to create a class scoped namespace. While variables can be scoped in classes.If you are using
#definethose 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.Also for same reasons mentioned in #2, while debugging
#definewon’t provide much of an help really.Hence it is much better idea to use
constvariables instead of a#define.They are superior to
#definein all above mentioned aspects.Only areas where#definecan be really helpful are where you need actual textual replacement in code or in defining include header guards.One reason that comes to my mind is, In C(unlike C++)
constdeclarations do not produce constant expressions.Which means prior to introduction of Variable length arrays in C standard one cannot write something like:because in C
max_valis 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: