macro

I knew what is macro and where we can use it.
But I am confused what's the real benifits of using macro?

Is ther any advantages of using it?

Please friends explain some one.
They have mostly disadvantages compared to other possibilities in C++. C had less features, and thus the preprosessor had a creater role.
not cleared.
Macros are like #defines on steroids.

I recently used it to make my life easier. I had to grab data from nested arrays, like:

foo = some_array[bar][another_array[get_index()]];

I needed this expression over and over again. So instead of writing it out all the time, I created a macro:

#define GET_STUFF(bar) (some_array[bar][another_array[get_index()]])

That made the code less cluttered.

BUT !!! I'd still recommend using an inline function for that (I didn't for other reasons):

1
2
3
inline int get_stuff(const int& bar){
	return some_array[bar][another_array[get_index()]];
}


That is basically the same thing but in a more modern and clean way. It might also help the optimizer a little (not sure about that).

What's inline, you ask?
http://www.cplusplus.com/doc/tutorial/functions/
Look for section "Inline functions".


As keskiverto stated, #define is a holdover from C. #defines were (and still are) a preprocessor facility that simply perform text substitution. They can appear to simplify your code, or they can make you code more difficult to read. #defines have global scope so they can unexpected consequences if used where not intended.

C++ templates are also a type of macro facility but with a better fit into the language.
Topic archived. No new replies allowed.