Home > Net >  How do I add a "case" to a switch statement programically in C?
How do I add a "case" to a switch statement programically in C?

Time:04-17

If I have a switch statement like this one:

switch(x)
{
    case 1:
        printf("Hello, world!");
    case 2:
        printf("Hello!");
}

How can I programically place new case statements inside the switch statements?

This is an example of what I want:

switch(x)
{
    case 1:
        printf("Hello, world!");
    case 2:
        printf("Hello!");
}
AddCaseStatementToSwitchStatement("case 3: printf(\"Hi!\")");

CodePudding user response:

You need a lookup table

struct err_def {
    int code;
    char* message;
};

int main() {

    struct err_def errs[] = { 
        {1,"Hello, world!"},
        {2,"Hello"}
    };
    int sz = 2;
    int errorCode = 2;
    char* msg;
    for (int i = 0; i < sz; i  ) {
        if (errs[i].code == errorCode) {
            msg = errs[i].message;
            break;
        }

    }
}

 

this one is static but you can do the same thing with a dynamically growing table

If the table gets big you can search it more efficiently by keeping it sorted and doing a binary chop on it

  •  Tags:  
  • c
  • Related