We have a library that provides access to buttons on a device. These buttons are enumerated to the rest of the system as things like "power button" and so on. This way, the rest of the applications don't have to worry about how the "power button" is implemented.
We build this library using a few configuration directives that look like this (simplified):
#define BUTTON_COUNT 2
#define BUTTON_0_NAME "power"
#define BUTTON_1_NAME "reset"
#define BUTTON_2_NAME NULL
The question is, at some point I want to fetch the name of button 1. Ideally, I would do this by creating a function like get_button_name(int index)
. The problem is, I can't find a good way to get at the numbered config options in that function. The current implementation looks like:
const char* get_button_name(int index) {
switch (index) {
case 0: return BUTTON_0_NAME;
case 1: return BUTTON_1_NAME;
case 2: return BUTTON_2_NAME;
}
return NULL;
}
The trouble is, this code is shared for many devices, so the number of supported buttons will continue to increase. That means changing this function and all the devices that pull it in have to add #define
's for the new buttons.
What I'd really prefer (although I'm don't think it's possible with the pre-processor) is something like:
const char* get_button_name(int index) {
if (index < BUTTON_COUNT) {
return BUTTON_ ## index ## _NAME;
}
return NULL;
}
Any ideas for a better solution?