Initializing statement for if/switch/foreach

There are several statements in C++ whose syntax was modified in recent versions of the standard. I refer here to the if and switch statements that were modified in C++17 to include initializing statements, and the range-based for loop that supports the same as of C++20. Their general form is shown in the following table:

Express one of multiple options in a nice way

We often find ourselves writing if statements where a variable is compared with several values either to check if it matches one of them or that it doesn’t match any. Here is an example:

int option = ...;

// at lease a value is matched
if (option == 12 || option == 23 || option == 42)
{
   std::cout << "it's a good option\n";
}

// no value is matched
if (option != 12 && option != 23 && option != 42)
{
   std::cout << "it's a bad option\n";
}

This example has three comparison values for each case, but it could be 5, or 10, or any number. If it’s too many then perhaps a different approach should be taken. However, the question is, how do we express this in a simpler way in C++, rather than a long if condition?

The choice between typename and class

When working with C++ templates, you have probably seen typename and class used interchangeably. Is there a difference between them? This post will explain when these two keywords can be used in templates. Let’s consider the following example: In this context, when declaring a type template parameter, there is no difference, they are interchangeable. They…