Home > Articles

This chapter is from the book

17 4.9 C++17 Selection Statements with Initializers

17 Earlier, we introduced the for iteration statement. In the for header’s initialization section, we declared and initialized a control variable, which limited that variable’s scope to the for statement. C++17’s selection statements with initializers enable you to include variable initializers before the condition in an if or ifelse statement and before the controlling expression of a switch statement. As with the for statement, these variables are known only in the statements where they’re declared. Figure 4.7 shows ifelse statements with initializers. We’ll use both ifelse and switch statements with initializers in Fig. 5.5, which implements a popular casino dice game.

 1   // fig04_07.cpp
 2   // C++17 if statements with initializers.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      if (int value{7}; value == 7) {
 8         cout << "value is " << value << "\n";
 9      }
10      else {
11         cout << "value is not 7; it is " << value << "\n";
12      }
13
14      if (int value{13}; value == 9) {
15         cout << "value is " << value << "\n";
16      }
17      else {
18         cout << "value is not 9; it is " << value << "\n";
19      }
20   }
value is 7
value is not 9; it is 13

Fig. 4.7 C++17 if statements with initializers.

Syntax of Selection Statements with Initializers

For an if or ifelse statement, you place the initializer first in the condition’s parentheses. For a switch statement, you place the initializer first in the controlling expression’s parentheses. The initializer must end with a semicolon (;), as in lines 7 and 14. The initializer can declare multiple variables of the same type in a comma-separated list.

Scope of Variables Declared in the Initializer

Any variable declared in the initializer of an if, ifelse or switch statement may be used throughout the remainder of the statement. In lines 7–12, we use the variable value to determine which branch of the ifelse statement to execute, then use value in the output statements of both branches. When the ifelse statement terminates, value no longer exists, so we can use that identifier again in the second ifelse statement to declare a new variable known only in that statement.

To prove that value is not accessible outside the ifelse statements, we provided a second version of this program (fig04_07_with_error.cpp) that attempts to access variable value after (and thus outside the scope of) the second ifelse statement. This produces the following compilation errors in our three compilers:

  • Visual Studio: 'value': undeclared identifier

  • Xcode: error: use of undeclared identifier 'value'

  • GNU g++: error: 'value' was not declared in this scope

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.