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

If and Switch local scoped variables

There is an interesting new feature that allows you to declare a local variable bound to the if and switch statements' block of code. The scope of the variable used in the if and switch statements will go out of scope outside the respective blocks. It can be better understood with an easy to understand example, as follows:

#include <iostream>
using namespace std;

bool isGoodToProceed( ) {
return true;
}

bool isGood( ) {
return true;
}

void functionWithSwitchStatement( ) {

switch ( auto status = isGood( ) ) {
case true:
cout << "\nAll good!" << endl;
break;

case false:
cout << "\nSomething gone bad" << endl;
break;
}

}

int main ( ) {

if ( auto flag = isGoodToProceed( ) ) {
cout << "flag is a local variable and it loses its scope outside the if block" << endl;
}

functionWithSwitchStatement();

return 0;
}

The preceding code can be compiled and the output can be viewed with the following commands:

g++-7 main.cpp -std=c++17
./a.out

The output of the preceding program is as follows:

flag is a local variable and it loses its scope outside the if block
All good!
主站蜘蛛池模板: 建昌县| 收藏| 中牟县| 阿鲁科尔沁旗| 罗甸县| 阿克陶县| 招远市| 平乐县| 崇明县| 蚌埠市| 景泰县| 巧家县| 报价| 通江县| 左贡县| 明溪县| 桐梓县| 仁布县| 井冈山市| 长阳| 尤溪县| 延吉市| 缙云县| 遂昌县| 富川| 伊宁市| 湟中县| 象州县| 靖安县| 胶南市| 齐齐哈尔市| 吉安市| 松江区| 镇康县| 齐河县| 海城市| 宽甸| 蕉岭县| 鸡东县| 梅河口市| 五原县|