Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value lookup table in C by strings?

Tags:

c

If I have a set of small string values, and I want to fetch a numeric value to represent them, what's the best way to do this via a lookup table?

If I were only needing to do a straight look up, I know the optimal solution would just be a series of if statements:

if (strcmp(str, "foo") == 0)
    tmp = FOO;
else if (strcmp(str, "bar") == 0)
    tmp = BAR;

But, I ask this because these small string values represent an attribute in a small project I'm writing in C, and the attributes can be read-only or read-write (no write-only for now, maybe never).

So what I currently do just to make sure things work is have a lookup function comprised of an if-then clause like above to look up which values are read-only, and a second functions that looks up which values are read-write. But this is large and ugly to me.

I'm thinking, have three functions instead. One function is the lookup function, and it returns an int value that is the numeric form of the string. But this lookup function can also take a flag that determines whether it fetches a read-only value, or a read-write value. If a write operation is done on a value that is really read-only, the function will return -EINVAL (or something equivalent).

The other two functions, now still the read and write, just call this lookup function, passing in a string of the value, and the flag that determines whether they're for reading or writing.

Thing is, I don't know how this is modeled in C (if it can be modeled), and searching Google is tiresome with all the content farms ripping this place off (and giving me C++/C# answers instead).

So this is how I think it'll look:

int lookup_func(const char *name, const char *flag) {
    int tmpval = 0;

    /* code to do the lookup. */

    if (tmpval == 0)
        return -EINVAL;
    else
        return tmpval;
}

int get_readonly_bit(const char *name) {
    return lookup_func(name, "ro");
}

int get_readwrite_bit(const char *name) {
    return lookup_func(name, "rw")
}

Thoughts? The idea is to reduce code size by not repeating the if-then branches for these two functions, which differ slightly in overall design, and simply let some kind of a lookup function figure out what function this value serves.

like image 950
Kumba Avatar asked Mar 04 '11 12:03

Kumba


1 Answers

Do you not consider just putting a table in? A hash table is also fine if there are lots of properties.

int lookup(const char *name)
{
  typedef struct item_t { const char *name; int writable; int value; } item_t;
  item_t table[] = {
    { "foo", 0, FOO },
    { "bar", 1, BAR },
    { NULL, 0, 0 }
  };
  for (item_t *p = table; p->name != NULL; ++p) {
      if (strcmp(p->name, prop_name) == 0) {
          return p->value;
      }
  }
  return -EINVAL;
}
like image 133
patthoyts Avatar answered Nov 15 '22 18:11

patthoyts