Last update: mid-2006

Optimized for Firefox 3 on CRT!

Download | Theory | Bugs | License | Examples | Home

Switching on strings in standard C
SOS home page

NEW! The development version of sos (nsos) generates code which can be used to process attribute/value pairs! Useful for program configuration files! For example, this input will generate the following output.

sos blurb

Switching on strings means using strings in the case labels of switch statements. Unfortunately C standards allow only integral constants in case labels, a severe restriction. Sos provides a convenient safe workaround this restriction.

Sos assisted code is clearer and more efficient than if-else chains using "strcmp" conditionals and probably other methods.

Technical description

Sos is a collection of simple string to integer encoding functions with a user interface that can generate either:

The functions and the user interface are useful for an implementation of "switching on strings" in standard C. This feature is useful, for example, in parsing config files of the form "name=value" (especially when there is a finite number of legal values).

The relevant encoding function should be lifted into the program with the GNU general license. The user interface should be used to generate useful code (see examples).

Sos version 0.5 supports by default strings assembled from the identifier character set {a-z, '_', 0-9, A-Z}. With the "-f" option the full 8-bit range (except '\0') is supported.

Sos works on platforms where the C compiler supports the "long long int" type in switch control expressions and case labels. All free operating systems with a free C compiler seems to qualify. A future sos version may support other platforms and compilers.

Other good ways to implement switching on strings are to add sos like capability to the C pre-processor or use a special purpose pre-processor.

future directions

sos vs. gperf

Why don't we use gperf hash functions?

gperf generates excellent keyword recognizer code that may include switch statement(s). It was not designed to support switching on strings and is thus less suitable and convenient for this very special purpose.

Historical links