官术网_书友最值得收藏!

Initializers in if/switch statements

In C++17, it is now possible to define a variable and initialize it in the definition of an if and switch statement, as follows:

#include <iostream>

int main(void)
{
if (auto i = 42; i > 0) {
std::cout << "Hello World\n";
}
}

// > g++ scratchpad.cpp; ./a.out
// Hello World

In the preceding example, the i variable is defined and initialized inside the if statement using a semicolon (;) inside the branch itself. This is especially useful for C- and POSIX-style functions that return error codes, as the variable that stores the error code can be defined in the proper context.

What makes this feature so important and useful is that the variable is only defined when the condition is met. That is, in the preceding example, i only exists if i is greater than 0.

This is extremely helpful in ensuring that variables are available when they are valid, helping to reduce the likelihood of working with an invalid variable. 

The same type of initialization can occur with switch statements as follows:

#include <iostream>

int main(void)
{
switch(auto i = 42) {
case 42:
std::cout << "Hello World\n";
break;

default:
break;
}
}

// > g++ scratchpad.cpp; ./a.out
// Hello World

In the preceding example, the i variable is created only in the context of the switch statement. Unlike the if statement, the i variable exists for all cases, meaning the i variable is available in the default state, which could represent the invalid state. 

主站蜘蛛池模板: 荣昌县| 毕节市| 伊川县| 新河县| 黄大仙区| 乌恰县| 柞水县| 宜良县| 漳浦县| 营口市| 沾益县| 武川县| 博客| 通江县| 巢湖市| 林芝县| 临海市| 宜良县| 新闻| 丰县| 静宁县| 大石桥市| 霞浦县| 屏东市| 文成县| 锡林浩特市| 鞍山市| 兴国县| 梓潼县| 论坛| 客服| 资阳市| 邵阳市| 丰顺县| 彭山县| 隆子县| 民乐县| 米脂县| 湟源县| 惠东县| 梧州市|