Init Statement for if and switch
Explore the use of init statements in C++17 with if and switch structures. Understand how defining variables within these statements limits their scope to the conditional blocks, preventing leakage and enhancing code clarity. This lesson helps you write more readable and maintainable conditional code using the latest C++17 features.
We'll cover the following...
C++17 provides new versions of the if and switch statements:
if (init; condition)
And
switch (init; condition)
In the init section you can specify a new variable, similarly to the init section in for loop. Then check the variable in the condition section. The variable is visible only in if/else scope.
To achieve a similar result, before C++17 you had to write:
Please notice that val has a separate scope, without that it ‘leaks’ to enclosing scope.
Now, in C++17, you can write:
Notice that val is visible only inside the if and else statements, so it doesn’t ‘leak.’
condition
might be any boolean condition.
Here is an example:
Why is this useful? We’ll discuss and example in the next lesson.