Introduction
Many languages know "switch case
" statement for string
s but C doesn't. Most implementations (i.e., command line parsers) use the "if else
" statements.
Background
I have been using the following code for many years. But it may be slower sometimes but can be faster in other circumstances. The discussion will be about the use in case of speed or about the case of neat code.
Using the Code
Everybody knows to switch a case by compare string
which causes to compare every string
in the compare list in the worst case. Much more neat is a real "switch case
" statement that can jump directly to the code to execute. But in reality, there is no great difference.
Conventional "if else
" block:
if( 0==_tcscmp( <option1_string>, <compare_option> )
{
}
if( 0==_tcscmp( <option2_string>, <compare_option> )
{
}
else
{
}
Using the "switch case
" block:
switch( scase( <compare_option>, <literal_of_options>, <options_separator> ) )
{
case 0: do_on_case_0( ... ); break;
case 1: do_on_case_1( ... ); break;
default: break;
}
Simple comparison of "switch case
" and "if else
".
Let's start with "if else
":
if( 0==_tcscmp(__T("help"), parameter ) )
{
show_help();
}
else if( 0==_tcscmp(__T("input"), parameter ) )
{
_tcscpy( input_file, next_parameter );
}
else
{
}
The same with "switch case
":
switch( scase( parameter, __T("help|input"), __T('|') ) )
{
case 0:
show_help();
break;
case 1:
_tcscpy( input_file, next_parameter );
break;
default: break;
}
Points of Interest
The switch
for string
s is really comfortable to use on parsing parameters or tokenizers. But sometimes, it may be slower than "if else
".