C++ 17 – init statement inside if and switch
In C++ 17, it is allowed to use an initialization statement in the if condition and switch condition.
Check out this if statement. it == 2 is the condition. But we can initialize it to an expression and also keep its declaration.
if (auto it = valueone() * 2; it == 2) {
We need to terminate such a condition by a semicolon (;) and write the condition. The scope of the variable is within the if else-if else block.
Consider the below switch statement. We can initialize it variable with an expression and also keep its declaration.
switch (int it = valueone() * 2; it) {
We need to terminate such a condition by a semicolon (;) and write the condition. The scope of the variable is within the switch block.
The above example is a simple one to see the usage. Consider this below usage inside an if condition, and you can see how it reduces the complexity.
if (auto it = names.find("Bob"); it != names.end()) {
The variable “it” is initialized to the position where “Bob” is found inside the names container. And then it checks for if the end of elements is reached in the actual condition.
We can use more complex expressions in the init statement, such as conditional operators.
Let us examine the complete program to see the usage of the init statements in C++ 17 in if and switch. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/init_in_if_switch.cpp.
$ cat init_in_if_switch.cpp
#include <iostream>
int valueone() {
return 1;
}
int main() {
// Using an init statement in an if statement
if (auto it = valueone() * 2; it == 2) {
std::cout << "it is 2" << std::endl;
}
// Using an init statement in a switch statement
switch (int it = valueone() * 2; it) {
case 2:
std::cout << "it is 2" << std::endl;
break;
default:
std::cout << "default" << std::endl;
break;
}
return 0;
}
You can compile and run the program as below using C++ 17-supported compiler.
$ g++ -std=c++17 init_in_if_switch.cpp -o init_in_if_switch
$ ./init_in_if_switch
it is 2
it is 2
You can also try the C++ 14 compiler. You can see that errors come in the compilation as this is a feature supported only by C++ 17 and not before.
$ g++ -std=c++14 init_in_if_switch.cpp -o init_in_if_switch
init_in_if_switch.cpp: In function ‘int main()’:
init_in_if_switch.cpp:9:9: warning: init-statement in selection statements only available with ‘-std=c++17’ or ‘-std=gnu++17’
9 | if (auto it = valueone() * 2; it == 2) {
| ^~~~
init_in_if_switch.cpp:14:13: warning: init-statement in selection statements only available with ‘-std=c++17’ or ‘-std=gnu++17’
14 | switch (int it = valueone() * 2; it) {
| ^~~