Originally this had to be the final paragraph of another question (this one), but I noticed that the topics were not so similar and consequently I thought of posting another one.
What I'm trying to accomplish is to make an automated system to compile some actions in an easy way.
For instance, instead of writing
switch (var)
{
case SM_1:
printf("Case 1");
break;
case SM_2:
printf("Case 2");
break;
case SM_3:
printf("Case 3");
break;
}
it would be easier for me to write something like
#define CASES
#define CreateCaseX(s,l) CASES += \
case s: \
printf(l); \
break;
CreateCaseX(SM_1, "Case 1")
CreateCaseX(SM_2, "Case 2")
CreateCaseX(SM_3, "Case 3")
...
switch(var)
{
CASES
}
I don't expect the CASES +=
statement to actually work, but... Is there some similar construct I can use in the preprocessor to add some actions (function calls, switch cases, ...) to a list and then let it write them all at once?
EDIT: I thought I had well fixed my problem boundaries, but looking at some answers and comments I noticed that this question could be interpreted in different ways. So please forgive me, now I'll try to detail things better.
I'm writing a simple state machine. Whenever I add a state, I have to perform different code modifications, such as
- add the state to the enumeration
- add the state name in the switch case construct that returns the name of the current state
- add the action to be performed when that state is the current one
For instance, I can have these lines in my file:
enum {
SM_Case_1,
SM_Case_2,
SM_Case_3
} currentState;
void printState()
{
switch (currentState)
{
case SM_Case_1:
printf("State 1");
break;
case SM_Case_2:
printf("State 2");
break;
case SM_Case_3:
printf("State 3");
break;
}
}
void executeAction()
{
switch (currentState)
{
case SM_Case_1:
// Do nothing
break;
case SM_Case_2:
globalVariable += 10;
break;
case SM_Case_3:
printf("Error");
break;
}
}
It is much easier (and easier to maintain) in my opinion to have a macro dealing with this, such as:
#define ENUMS
#define NAMES_CASES
#define ACTION_CASES
#define CreateState(s,l,a) \
ENUMS += s, \
NAMES_CASES += case s: printf(l); break; \
ACTION_CASES += case s: a; break;
CreateState(SM_Case_1,"State 1",{})
CreateState(SM_Case_2,"State 2",globalVariable += 10)
CreateState(SM_Case_3,"State 3",printf("Error"))
enum {
ENUMS
} currentState;
void printState()
{
switch (currentState)
{
NAMES_CASES
}
}
void executeAction()
{
switch (currentState)
{
ACTION_CASES
}
}
I noticed that it was tricky to write a feasible syntax, so probably such a technique does not exist, but... If there is, it's useful to know..