Using Strings with a Switch


The following macros help to achieve the switch-case on a string.

#define STR_SWITCH(str)  {
        TCHAR* __ps = (TCHAR*)((const TCHAR*)str);
        while(1) {

#define STR_SWITCH_END()  break; } }

#define STR_CASE(str) if(0 == _tcsicmp(__ps,((const TCHAR*)str)))

#define STR_CASE_EXACT(str)  if( 0 == _tcscmp( __ps,
                               ((const TCHAR*)str) ) )

#define DEFAULT_CASE()


How do you use these macros? Go through the following piece of code.

  CString sSwitch("bbbb");
  CString sCase("AAAA");

  STR_SWITCH(sSwitch)      //Start of switch
  {                        //Opening and closing braces
                           //NOT MANDATORY for switch.
    {                      //Opening and closing braces
                           //MANDATORY for case.
      AfxMessageBox("In first case statement");
      break;               //break has to in braces of case
    }                      //Opening and closing braces
                           //MANDATORY for case.

  break;                   //Illegal break -- The code works,
                           //but the output....?????

  sCase = _T("bbbb");      //Statements allowed here ;)

      AfxMessageBox("In second case statement");
                           //Default handling if any
  }                        //Opening and closing braces
                           //NOT MANDATORY for switch
  STR_SWITCH_END()         //MANDATORY statement

STR_CASE() -> Perform a lowercase comparison of strings.
STR_CASE_EXACT() -> Compares strings, matches the
                     case of the characters.
DEFAULT_CASE() -> Default case for the switch.

Note the following requirements:

  1. The “break” statement has to be inside the scope for the STR_CASE, STR_CASE_EXACT, or DEFAULT_CASE.
  2. Fall through for case statements is not allowed with this switch case.
  3. Statements between two cases are allowed. Be careful while modifying the string on which the switch is performed.

More by Author

Must Read