- Hands-On System Programming with C++
- Dr. Rian Quinn
- 242字
- 2021-07-02 14:42:38
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.
- 數據庫技術與應用教程(Access)
- Python數據挖掘:入門、進階與實用案例分析
- 深度剖析Hadoop HDFS
- Remote Usability Testing
- Oracle PL/SQL實例精解(原書第5版)
- MATLAB Graphics and Data Visualization Cookbook
- 大數據治理與安全:從理論到開源實踐
- 數據分析師養成寶典
- SQL Server 2012實施與管理實戰指南
- Oracle 11g+ASP.NET數據庫系統開發案例教程
- openGauss數據庫核心技術
- 中國云存儲發展報告
- Oracle 內核技術揭密
- 數據挖掘與數據化運營實戰:思路、方法、技巧與應用
- 一本書講透數據治理:戰略、方法、工具與實踐