I would like to get feedback on a "switching on strings" utility:
http://shum.huji.ac.il/~agay/sos
Since it's GPL I won't look at the source (I use the zlib licence which
is free and non-contaminating), but looking at the description it seems
feasible. However, it has some disadvantages:
Not all compilers support long long in switches (indeed, C89 compilers
don't usually support long long at all; gcc -ansi -pedantic gives a
warning).
Only 10 characters (8 if all characters are allowed in the string) are
supported.
You need a separate list of strings (and defined labels) from the
labels in the code.
Since the numbers for the #defines are presumably either
hand calculated or are generated by a program from the input strings, if
the latter I would use a code generator to generate the encoding
function from the source, similar to what is done for gettext, scanning
through the code, so I'd have switches looking something like:
switch (encodeString(str))
{
case RED("red"):
case BLUE("blue"):
case SOMETHING_ELSE("another"):
...
}
The generator would go through looking for appropriate switches, and
would then define macros as found in the case labels:
int encodeString(char *);
#define RED(x) 1
#define BLUE(x) 2
#define SOMETHING_ELSE(x) 3
Those would be output to a header file, and a generator function (using
a "perfect hash" of some kind, or possibly a state table as in lex if I
were after efficiency) output to a C file to be included in the build.
The generator could be quite simplistic in parsing the source, for
instance ignoring anything except cases starting on a new line (with
leading spaces) and any cases without a string argument to the macro.
(In fact now you've given me the idea I might write one...)
Commenting on your example (which isn't GPL), I notice that if it hits
EOF it goes into an infinite loop, since you don't check the return
value of scanf...
(Why do you have a 900 second refresh on every page?)
Chris C