Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

C Programming

Name: Anonymous 2012-04-19 13:05

Hi /prague/
I'm programming in C and writing a little interactive program.
What's the best way to execute a function / piece of code depending on a string ? I could write a bunch of }else if(!strcmp(s, foo)){ but I find this hideous.
Any suggestions ?

Name: Anonymous 2012-04-19 13:13

Branching with !strcmp() is only efficient if there aren't many potential strings to compare. You should also only ever use this in situations requiring user input. Sage for non-Lisp.

Name: Anonymous 2012-04-19 13:27

It requires user input.
Also, it isn't /lisp/, it's /prog/.

Name: Anonymous 2012-04-19 14:27


struct command_handler_lst {
  struct command_handler_lst * next;
  char * name;
  void (*handler)();
};

for (; node; node = node->next) {
  if (strcmp(node->name, input) {
    node->handler();
  }
}

Name: Anonymous 2012-04-19 14:28

>>2

Could you elaborate a bit further? What would be a good alternative? Hashing the strings?

Thanks.

Name: Anonymous 2012-04-19 14:33

>>5

How many strings are we talking about?

Name: Anonymous 2012-04-19 14:39

>>5

Well, as you said, a number large enough for not justifying the if-chain alternative. Is 1000 strings enough for that?

Name: Anonymous 2012-04-19 14:39

>>7
Sorry. Meant to refer >>6.

Name: Anonymous 2012-04-19 15:01

if you have a shitton of strings:


struct node {
  struct node * children[256];
  char current_index;
  char * rest;
  void (*handler)();
};


Now simply walk down the tree by indexing the structs children with the first char of the string, stop when you reach a NULL and compare the rest of the input with the rest-field of the node.

So, rest and handler should be set only on leaf nodes. I guess the top of your mapping would be a node without an index.

Name: Anonymous 2012-04-19 15:02

>>9
insertion is left as an exercise for the reader.

Name: Anonymous 2012-04-19 16:07

A delicious trie, using a string as key to lookup a function pointer to the handler for that string

Check em<---

Name: Anonymous 2012-04-19 22:20

>>1
So you basically want a script compiler/interpreter or what?

Name: Anonymous 2012-04-19 23:35

use a hash table or use a trie: hard code it for leat ness

Name: Anonymous 2012-04-20 4:28

Bump.

Yeah, I first made something like >>4
But the trie seems nice to me. Thank you /prague/ !

Name: Anonymous 2012-04-20 4:32

>>10
[b]Insert your dick.[/b]

Name: Anonymous 2012-04-20 14:35

Trie or hash table.

Name: Anonymous 2012-04-20 22:50

Use lex.

Name: bampu pantsu 2012-05-29 4:31

bampu pantsu

Don't change these.
Name: Email:
Entire Thread Thread List