Skip to content

Instantly share code, notes, and snippets.

@lorsi96
Last active May 9, 2021 01:00
Show Gist options
  • Save lorsi96/142046e191c29aa7a35207a9d54707f0 to your computer and use it in GitHub Desktop.
Save lorsi96/142046e191c29aa7a35207a9d54707f0 to your computer and use it in GitHub Desktop.
X Macros Example
#include <stdio.h>
// void/void function wrapper to make code readable.
typedef void (*runnable_t)();
// Animal functions definitions.
void bark() {
printf("Guau!\n\r");
}
void mew() {
printf("Miau!\n\r");
}
void croak() {
printf("Ribit!\n\r");
}
// Animal groups declaration.
typedef enum {
MAMMAL,
AMPHIBIAN
} animal_group_t;
// Table associating animals with their sounds.
#define ANIMAL_TABLE(XX) \
XX(DOG, MAMMAL, bark) \
XX(CAT, MAMMAL, mew) \
XX(FROG, AMPHIBIAN, croak)
// Definition of animal type.
typedef enum animal {
#define XX(animal, group, onomat) animal,
ANIMAL_TABLE(XX)
#undef XX
ANIMAL_N
} animal_t;
// Definition of animal functions table.
runnable_t animal_functions[] = {
#define XX(animal, group, onomat) onomat,
ANIMAL_TABLE(XX)
#undef XX
};
// Animal Groups definitions.
animal_group_t animal_groups[] = {
#define XX(animal, group, onomat) group,
ANIMAL_TABLE(XX)
#undef XX
};
// Test main
int main() {
if(animal_groups[DOG] == MAMMAL) {
animal_functions[DOG]();
}
if(animal_groups[FROG] == AMPHIBIAN) {
animal_functions[FROG]();
}
if(animal_groups[CAT] == AMPHIBIAN) {
animal_functions[CAT]();
} else {
printf("Hey! Cats aren't amphibians");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment