Selection Initialization allows for optional variable initialization within if and switch statements – similar to that used within for statements.
for (int a = 0; a < 10; ++a) {
// for body
}
Here the scope of a is limited to the for the statement. But consider:
{
auto a = getval();
if (a < 10) {
// Use a
}
Here variable a is used only within the if statement but has to be defined outside within its own block if we want to limit its scope. But in C++17 this can be written as:
if (auto a = getval(); a < 10) {
// Use a
}
Which follows the same initialization syntax as the for the statement – with the initialization part separated from the selection part by a semicolon (;). This same initialization syntax can similarly be used with the switch statement. Consider:
switch (auto ch = getnext(); ch) {
// case statements as needed
}
Which all nicely helps C++ to be more concise, intuitive and correct!
for (int a = 0; a < 10; ++a) {
// for body
}
Here the scope of a is limited to the for the statement. But consider:
{
auto a = getval();
if (a < 10) {
// Use a
}
Here variable a is used only within the if statement but has to be defined outside within its own block if we want to limit its scope. But in C++17 this can be written as:
if (auto a = getval(); a < 10) {
// Use a
}
Which follows the same initialization syntax as the for the statement – with the initialization part separated from the selection part by a semicolon (;). This same initialization syntax can similarly be used with the switch statement. Consider:
switch (auto ch = getnext(); ch) {
// case statements as needed
}
Which all nicely helps C++ to be more concise, intuitive and correct!
Comments
Post a Comment