Let's take a silly example:
#define MAX_NUM_BITES 20
...
void live_another_day() {
...
int num_bites = 0;
...
eat_little_pig(&num_bites);
if (num_bites>MAX_NUM_BITES) {
printf("You shouldn't more than %d bites. Otherwise, you will get fat!");
return;
}
...
eat_grandma(&num_bites);
if (num_bites>MAX_NUM_BITES) {
printf("You shouldn't more than %d bites. Otherwise, you will get fat!");
return;
}
...
eat_red_riding_hood(&num_bites);
if (num_bites>MAX_NUM_BITES) {
printf("You shouldn't more than %d bites. Otherwise, you will get fat!");
return;
}
...
}
That example will read better if we define this macro:
#define EXIT_WITH_ERROR_MESSAGE_IF_FULL(num_bites) \
if (num_bites>MAX_NUM_BITES) { \
printf("You shouldn't more than %d bites. Otherwise, you will get fat!"); \
return; \
}
void live_another_day() {
...
int num_bites = 0;
...
eat_little_pig(&num_bites);
EXIT_WITH_ERROR_MESSAGE_IF_FULL(num_bites)
...
eat_grandma(&num_bites);
EXIT_WITH_ERROR_MESSAGE_IF_FULL(num_bites)
...
eat_red_riding_hood(&num_bites);
EXIT_WITH_ERROR_MESSAGE_IF_FULL(num_bites)
...
}
My question is: should I take it a step further and not even pass num_bites to the macro?
#define EXIT_WITH_ERROR_MESSAGE_IF_FULL() \
if (num_bites>MAX_NUM_BITES) { \
printf("You shouldn't more than %d bites. Otherwise, you will get fat!"); \
return; \
}
Or is that not good coding practice?
Subsidiary question: is it good coding practice not to follow the macro call with a ';' ?