Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Discussion About switch ... case Statement for Strings

2.13/5 (5 votes)
31 May 2016CPOL 9.1K   17  
switch ... case statement for strings

Introduction

Many languages know "switch case" statement for strings 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:

C++
//
// the switch case by if else
//
if( 0==_tcscmp( <option1_string>, <compare_option> )
{
  // do if case match
}
if( 0==_tcscmp( <option2_string>, <compare_option> )
{
  // do if case match
}
else
{
  // do anything else
}

Using the "switch case" block:

C++
//
// the switch case by switch (parameters are strings)
//
switch( scase( <compare_option>, <literal_of_options>, <options_separator> ) )
{
  case 0: do_on_case_0( ... ); break;
  case 1: do_on_case_1( ... ); break;
  default: /* do anything else */ break;
}

Simple comparison of "switch case" and "if else".

Let's start with "if else":

C++
if( 0==_tcscmp(__T("help"), parameter ) )
{
  show_help();
}
else if( 0==_tcscmp(__T("input"), parameter ) )
{
  _tcscpy( input_file, next_parameter );
}
else
{
  // unknown parameter
}

The same with "switch case":

C++
switch( scase( parameter, __T("help|input"), __T('|') ) )
{
  case 0: /* help */
   show_help();
  break;

  case 1: /* input */
   _tcscpy( input_file, next_parameter );
  break;

  default: /* unknown parameter */ break;
}

Points of Interest

The switch for strings is really comfortable to use on parsing parameters or tokenizers. But sometimes, it may be slower than "if else".

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)