Search code examples
cdesign-patternsembeddedembedded-linux

How to reduce or replace the else if statements in C language?


I'm using the code as shown below

  if (strcmp(oid, ".1.3.6.1.4.1.53864.1.1.0") == 0) 
  {
      return 1;
  } 
  else if (strcmp(oid, ".1.3.6.1.4.1.53864.1.2.0") == 0) 
  {
      return 2;
  }
  ...
  else if (strcmp(oid, ".1.3.6.1.4.1.53864.1.n.0") == 0) 
  {
      return n;
  }

Now the problem is updated n value is 250. Can anyone please give me any idea to reduce this else if statement?

I tried to search on StackOverflow but those answers are related to the other languages and I want an idea that I can implement in the C language.


Solution

  • You can use strncmp() to match the prefix (".1.3.6.1.4.1.53864.1."), extract the text value say by using strchr() and convert it with strtol() for the return, and match the suffix (".0"):

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int oid_sub(const char *s) {
        const char prefix[] = ".1.3.6.1.4.1.53864.1.";
        if(strncmp(s, prefix, sizeof(prefix) - 1))
            return -1;
        char *end;
        // check n for under and overflow?
        int n = strtol(s + sizeof(prefix) - 1, &end, 10);
        const char suffix[] = ".0";
        if(end == s + sizeof(prefix) - 1 || strcmp(end, suffix))
            return -1;
        return n;
    }
    
    int main() {
        char *s = ".1.3.6.1.4.1.53864.1.42.0";
        printf("%d\n", oid_sub(s));
    }
    

    I would prefer a regex based solution:

    #include <regex.h>
    
    int oid_sub2(const char *s) {
        regex_t r;
        const char regex[] = "^\\.1\\.3\\.6\\.1\\.4\\.1\\.53864\\.1\\.([^.]+)\\.0$";
        if(regcomp(&r, regex, REG_EXTENDED))
            return -1;
        regmatch_t m[2];
        if(regexec(&r, s, 2, m, 0))
            return -1;
        return atoi(s + m[1].rm_so);
    }
    

    Note, atoi() fails with 0 on error, so you could tweak the regex to ensure it matches numbers or use strtol() as above (but no need to check the suffix as the regex already takes care of that).