Language feature: Initializers in if and switch statements

code

Syntax

How would we write the previous code before C++17? It would look something like this:

From the following code, we can see that result is added into the enclosing scope, even if we wanted to use it ONLY inside the if / else statement.

Using C++17 init statement, the value initialized before the condition to be evaluated is in the same scope as the if/else if/ else branches.

To be noted that the initialization in the if branch is also visible in all the other else branches.

Why it was needed?

Let’s say we want to search from a few entries in a map and display the values, if found. How would we get those iterators?

In order for this to work, we would have to either enclose each snippet into a separate scope, or to use unique names for variables.

With C++17, the code looks cleaner and easier to read and debug:

Leave a comment

Your email address will not be published.