Switch with Init-Statement Syntax

The C++17 init-statement syntax can be helpful when there is no implicit conversion to integral or enumeration type.

cppreference.com

Switch Statement

Before C++17

switch([condition])
{
case A:
...
default:
}

After C++17

switch([init-statement];[condition])
{
case A:
...
default:
}
  • Obviously, a switch statement can create a local object since C++17.
  • Therefore, using RAII in this scope is a smart strategy not only to make code tidy but to automatically recycle object using stack as well.

Example – Dialog

  • I think Dialog is a good example of the charm of this syntactic sugar because dialogs are usually created for getting user’s input and perform actions contingent on conditions, and then be destroyed.
C++
{
  auto dialog = Dialog{};
  switch (dialog.GetFeedback("Exit the program?"))
  {
  case Dialog::Confirm:
    exit(EXIT_STATE_USER_CONFIRMED);
    break;
  case Dialog::Cancel:
    break;
  case Dialog::NoResponse:
    LOG("Dialog no response!");
    break;
  default: assert(false);
  }
}
C++
switch (auto dialog = Dialog{}; 
dialog.GetFeedback("Exit the program?"))
{
case Dialog::Confirm:		    
  exit(EXIT_STATE_USER_CONFIRMED);
  break;
case Dialog::Cancel:
  break;
case Dialog::NoResponse:
  LOG("Dialog no response!");
  break;
default: assert(false);
}

Leave a Reply

Your email address will not be published. Required fields are marked *