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

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!
主站蜘蛛池模板: 阿坝县| 迁西县| 深圳市| 汉源县| 内乡县| 鹤峰县| 镇沅| 鹿邑县| 达拉特旗| 黑水县| 辽宁省| 田阳县| 湟中县| 凌源市| 信宜市| 门源| 大同县| 海阳市| 双柏县| 晋中市| 牡丹江市| 怀宁县| 丘北县| 天水市| 北票市| 宜春市| 永福县| 自贡市| 保山市| 伊宁市| 巴里| 大安市| 新密市| 河津市| 开阳县| 庐江县| 和硕县| 定边县| 宁强县| 昌邑市| 潍坊市|