I am usually not a fan of this type of answer, but I find it appropriate.
Do not do this! A very large switch statement is the smell of code. This indicates that some bad planning has occurred in your code, or some initially good design has grown out of control as the project volume has grown.
You should use the switch statement if you have a choice of several really different options. Like this:
void HandleCommand(unsigned char commadndByte) { switch (commandByte) { case COMMAND_RESET: Reset(); break; case COMMAND_SET_PARAMETERS: SetPID(commandValue[0], commandValue[1], commandValue[2]); ResetController(); SendReply(PID_PARAMETERS_SET); break; default: SendReply(COMMAND_HAD_ERROR); break; }
Does your switch statement really translate a program stream into hundreds of really different options? Or is it more like this?
void HandleCharacter(unsigned char c) { switch (c) { case 'a': c='A'; break; case 'b': c='B'; break; case 'c': c='C'; break; case 'd': c='D'; break; ... case 'w': c='W'; break; case 'x': c='X'; break; case 'y': c='Y'; break; case 'z': c='Z'; break; } }
Be that as it may, you can do it better with some sort of array. To save the answer in assembler, I will write it in C, but the concept is the same.
If each case of the switch includes a call to another function, then:
const void (*p[256]) (int x, int y) = {myFunction0, myFunction1, ... myFunction255}; void HandleCharacter(unsigned char c) { (*p[c])(); }
You could argue that an array of function pointers takes up a lot of memory. If it is const, then it should only accept FLASH, or RAM, and should occupy less FLASH than the equivalent switch statement;
Or, something like this might be more relevant. If each switch case involves the assignment of a different value, then:
char validResponses[256] = {INVALID, OK, OK, OK, PENDING, OK, INVALID, .... }; void HandleCharacter(unsigned char c) { sendResponse(validResponses[c]); }
In general, try to find the pattern in the switch statement; what is changing and what remains the same? Put what changes into an array and what remains unchanged in the code.