Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ coding standard #define header files

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.

like image 243
vis.15 Avatar asked Sep 02 '25 15:09

vis.15


1 Answers

#define are a bad practice because:

They don't have any Scope:

#defines 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 #definewidely 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]; 
like image 153
Alok Save Avatar answered Sep 05 '25 04:09

Alok Save