Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to shorten a long switch() statement?

I'm dealing with quite a lot of cases in my switch() statements and was wondering if there's any possible way I could shorten these. They take up a lot of space in my code and it's harder to navigate when there are 3-4 big chunks of these statements. Here's an example:

...important lines of code...

void foo(string bar, bool blam) {

     int v1 = stoi(bar);

     switch (v1) {
         case(11):
             if(blam) {
                exArr[1] = "A";
             } else {
                exArr[1] = "B";
             }
             break;

         case(12):
             if(blam) {
                 exArr[3] = "A";
             } else {
                 exArr[3] = "B";
             }
             break;

         ...many more cases...

         default:
             printElement();
             break;
}
...even more important code, which is dependent on the hard code above and hard to navigate...

I think you see the problem. Do you guys have any suggestions? Thanks in advance.

IMPORTANT EDIT:

Only the first 12 iterations change the characters of exArr. After that, it changes to another (existing) array, like ndArr, which takes another 12 iterations. This goes on for 4 arrays, so about 48 case statements.

like image 258
splashrt Avatar asked Sep 21 '19 18:09

splashrt


1 Answers

As @Alexander Zhang mentioned, if you have a particular algorithm you can use, the simplest solution to your problem would be similar to what @Ton van den Heuvel proposes.

If not, there is also the alternative of using a lookup table (referenced from here) if you have particular values that match up.

Eg.

#include <map>

.../

map<int,int> mapV1toIndex = {
    {11, 1}, 
    {12, 3},
    .../
};

void foo(string bar, bool blam) {
    int v1 = stoi(bar);
    exArr[mapV1toIndex[v1]] = (blam) ?  "A" : "B";
}

Also, if you wanted to use different string arrays each time, you could pass in the string array into foo like so to reuse the foo function:

void foo(string *pStrArray, string bar, bool blam) {
    int v1 = stoi(bar);
    pStrArray[mapV1toIndex[v1]] = (blam) ?  "A" : "B";
}

Edit: It is preferable to use std::map instead of a struct. Edited the code to use map, following this reference.

like image 192
Enthus3d Avatar answered Oct 05 '22 00:10

Enthus3d