Reputation: 6102
I'm reading some source code. And not only this source code, but also many others, use this kind of programming:
#define DO_BINOP(FN_NAME,TFLAG,OPER) \
void FN_NAME (bigint_stack &stack) { \
bigint right = stack.front(); \
stack.pop_front(); \
TRACE (TFLAG, "right = " << right); \
bigint left = stack.front(); \
stack.pop_front(); \
TRACE (TFLAG, "left = " << left); \
bigint result = left OPER (right); \
TRACE (TFLAG, "result = " << result); \
stack.push_front (result); \
}
DO_BINOP(do_add, '+', + )
They use define
to define a long-long string that acts as a function. I don't know what the benefit of doing this is, because this way makes the program harder to read, and harder to debug. I'm new to C, so I think this way must have some benefit, right?
Thanks.
Upvotes: 8
Views: 407
Reputation: 11547
Because otherwise you'd have a source code that looks like this:
void do_add (bigint_stack &stack) {
bigint right = stack.front();
stack.pop_front();
TRACE ('+', "right = " << right);
bigint left = stack.front();
stack.pop_front();
TRACE ('+', "left = " << left);
bigint result = left + (right);
TRACE ('+', "result = " << result);
stack.push_front (result);
}
void do_subtract (bigint_stack &stack) {
bigint right = stack.front();
stack.pop_front();
TRACE ('-', "right = " << right);
bigint left = stack.front();
stack.pop_front();
TRACE ('-', "left = " << left);
bigint result = left - (right);
TRACE ('-', "result = " << result);
stack.push_front (result);
}
Etcetera...
Now, if you want to add another TRACE, for example, you'd have to again copy-paste it to all of them.
What the author wanted, really, is to define a way to generate functions from a set of parameterized inputs, in such a way that the resulting functions are all similar but they behave in slightly different ways depending on the input given to generate them. It's called meta-programming. Very common in coding parsers, which I suspect is where this snippet came from.
Now, in other languages, a construct specific to that language might exist to do meta-programming like this in a cleaner way (templates, metaclass, etc). But for C, macro is it.
Upvotes: 12