Macros, When and When Not

What type of rule of thumb or Hueristics that you go by when you decide to defined and use a macro (besides compile time determination of what code is run).

Sometimes I use a macro for PI

1
2
3
4
5
6
7
#define PI 3.14....f //or for a simple function

#define MIN_VAL( a, b )( a < b ? a : b )
#define MAX_VAL( a, b )( a > b ? a : b )

but I've seen them used for array indexes which imo is dangerous and a bad practices for a large application.
 


when are they useful to you?
Last edited on
I think macros are very useful when you have some libraries or codes that can be configured dynamically depends on the OS, user preferences and so on.

Consider you have a math-library ( lets say the library is in source-form, not a dll) which offers many methods to solve a particle problem, how would you give the end user the possibility to choice his default or preferred method.

Lets say to find the inverse of matrix, your library offers many method and fucntions, but the easiest one may be

1
2
3
4
5
// let say MD2 is a 2d array
MD2 a(5,5);
a.randomize();
// the method calculating the inverse 
a.inv(); // which methods/algorithm does it use ? is the user enabled to define his default method 


I think in such cases the macros are very useful and powerful.

If you want to develop cross-platform library/codes you have to use macros.

you can see many example of macros in all C++ large library, as you mentioned from arrays, see also Blitz, eigen, armadillo, hasem and so on.
Last edited on
besides compile time determination of what code is run
I think therockon7throw missed this part.

I try to avoid macros. They don't follow scoping rules and gives terrible error messages.

Constants can be defined with the const keyword:
const float PI = 3.14....f

If inline functions is what you want you can use the inline keyword:
1
2
3
4
5
template <class T>
inline T min_val(const T& a, const T& b)
{
	return a < b ? a : b;
}


Last edited on
Only use a macro when nothing else will do.
which offers many methods to solve a particle problem, how would you give the end user the possibility to choice his default or preferred method.
Take a look at the strategy pattern.

M_PI in cmath. Use it.
ne555 wrote:
M_PI in cmath. Use it.

M_PI is not standard.
Topic archived. No new replies allowed.