Thursday, October 21, 2010

"switch...case" vs "if...else if" for String Handling

I posted to the Devx.com forum a suggestion for handling a string via "switch...case" instead of "if...else if" and asked expert opinion in June 2007:

We use C for developing embedded systems software. A function assigns a function pointer based on the "action_name", see LISTING 1. I don't like such "if...else if" statements although the below one is short and easy-to-follow. Consequently, I replaced the "if...else if" statements to a "switch-case" statement. Certainly, the new code is much longer, see LISTING 2. As I don't use function pointers, but call some static functions there are some other differences. The major issue is deciding what to do. Here, a string holds all the supported actions, namely "s_Actions". The "actions" enum lists the "index" of each "action_name" in this string. For example, "GetCurrentConnectionIDs" "action_name" starts at 17th character. Please note that I separated the action_names with "_".

The advantages of LISTING 2:
1. All the supported actions are clearly listed with the "s_Actions" string.
2. There is only one function call, namely strstr(), to decide what to do instead of N strcmp() calls.
3. The strstr() call works like a hash function as it converts a string to an index. Although, it takes more lines to write, the logic is to closer to how my brain works: I don't think in terms of "if...else if"s because as I know all the supported actions just by looking the "action_name", I decide what to do.

The disadvantages of LISTING 2:
1. It takes more lines and time to develop code.
2. It is necessary to assign "index" numbers manually and updating it may be a boring and error-prone task.

However, I personally prefer LISTING 2 over LISTING 1. What is your opinion? Thanks for your interest.

(All the debug related lines etc are deleted below)


Unfortunately, I haven't received much useful comment. I still believe the technique I suggested is better suited to the embedded systems.

No comments: