Using Strings with a Switch


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


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.


  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date