[techtalk] switch function in C (or how to read commandline args?)

Conor Daly conor.daly at oceanfree.net
Tue Jul 3 15:57:52 EST 2001


On Mon, Jul 02, 2001 at 08:17:58PM -0500 or so it is rumoured hereabouts, 
Jeff Dike thought:
> conor.daly at oceanfree.net said:
> > Now that's interesting.  So how do I tokenise the strings? 
> 
> OK, let's say you have an interpreted language, and a program being 
> interpreted has this in an inner loop:
> 	foo;
> 	bar;
> 	baz;
> 
> If you represent pieces of this program with strings, you'll end up with an 
> array like [ "foo", "bar", "baz" ] for that loop body.
> 
> The interpreter will need to do something like this for each iteration of that 
> loop:
> 	if(!strcmp(instruction, "foo")) do_foo();
> 	else if(!strcmp(instruction, "bar")) do_bar();
> 	else if(!strcmp(instruction, "baz")) do_baz();
> 	else if(!strcmp(instruction, "hoo")) do_hoo();
> 	else if(!strcmp(instruction, "ha")) do_ha();
> 
> which will be slow.
> 
> So, what's normally done instead is that when the program is read in, a 
> conversion like this happens:
> 	"foo;" -> FOO_INSTR
> 	"bar;" -> BAR_INSTR
> 	"baz;" -> BAZ_INSTR

So, I can do something like:

#define FORCE_SWITCH "--force"
#define CONFIG_SWITCH "-C"

and so on?
 
> where *_INSTR are #defined constants or enum constants.
> 
> So, now the inner loop is represented as this array : 
> 	[ FOO_INSTR, BAR_INSTR, BAZ_INSTR]
> 
> And the interpreter can be implemented using a switch:
> 
> 	switch(instruction){
> 	case FOO_INSTR:
> 		do_foo();
> 		break;
> 	case BAR_INSTR:
> 		do_bar();
> 		break;

and

	case FORCE_SWTICH:
		force=1;
		break;
	case CONFIG_SWITCH:
		strcpy(config_file_name, argv[2]);
		break;


> which will be a lot faster.
> 
> 				Jeff

Conor
-- 
Conor Daly <conor.daly at oceanfree.net>

Domestic Sysadmin :-)
---------------------
Faenor.cod.ie
  3:45pm  up 18 days, 16:02,  0 users,  load average: 0.08, 0.02, 0.01
Hobbiton.cod.ie
  3:52pm  up 18 days, 16:10,  1 user,  load average: 0.00, 0.00, 0.00




More information about the Techtalk mailing list