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

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!
主站蜘蛛池模板: 海安县| 古丈县| 囊谦县| 江川县| 张北县| 青浦区| 罗田县| 道孚县| 同心县| 宕昌县| 宜宾市| 巴中市| 德格县| 蒙自县| 蛟河市| 汾阳市| 都昌县| 山东省| 祁阳县| 南木林县| 安龙县| 竹北市| 庐江县| 沛县| 阜南县| 师宗县| 友谊县| 酒泉市| 东莞市| 介休市| 沙坪坝区| 旌德县| 勐海县| 庄河市| 宁津县| 旺苍县| 馆陶县| 新兴县| 垫江县| 大同市| 灌南县|