Tuesday, October 17, 2017

C++17: Initializers in if and switch statements

C++17 allows an initializer in if and switch statements. Here is an example:

#include <iostream>

int main()
{
  if (int i = 4; int j = 0)
  {
    std::cout << "Branch1 ";
  }
  else
  {
    std::cout << "Branch2 ";
  }

  if (int i = 0; int j = 5)
  {
    std::cout << "Branch1 ";
  }
  else
  {
    std::cout << "Branch2 ";
  }

  std::cout << ": ";

  switch (int i = 4; int j = 0)
  {
   case 0:
    std::cout << "Branch1 ";
    break;
   case 4:
    std::cout << "Branch2 ";
    break;
  }

  switch (int i = 0; int j = 5)
  {
   case 0:
    std::cout << "Branch1 ";
    break;
   case 5:
    std::cout << "Branch2 ";
    break;
  }
  std::cout << std::endl;
  return 0;
}
// Output: Branch2 Branch1 : Branch1 Branch2
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://www.modernescpp.com/index.php/cpp17-core

No comments:

Post a Comment