I want to simplify the following code:
switch (index)
{
case 1:
output = function1();
break;
case 2:
output = function2();
break;
case 3:
output = function3();
break;
....
Where index
is a compile time constant.
If I would use a precompiler macro, I would need to use it n
times, where n
is the number of cases. How can I reduce the above mentioned code to O(1) lines of code?
May be supermacro can slightly simplify your work. Simply create "counter.def" file with code:
COUNTER(1)
COUNTER(2)
COUNTER(3)
#undef COUNTER
Then in any case of using switch or any other construction with repeating counting
switch(index)
{
#define COUNTER(i) case i: output = function##i(); break;
#include "counter.def"
}