- Mastering C++ Programming
- Jeganathan Swaminathan
- 201字
- 2021-07-02 18:28:47
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!
推薦閱讀
- Offer來了:Java面試核心知識(shí)點(diǎn)精講(原理篇)
- Hadoop+Spark大數(shù)據(jù)分析實(shí)戰(zhàn)
- 精通網(wǎng)絡(luò)視頻核心開發(fā)技術(shù)
- SSM輕量級(jí)框架應(yīng)用實(shí)戰(zhàn)
- Python編程:從入門到實(shí)踐
- The Complete Coding Interview Guide in Java
- 運(yùn)用后端技術(shù)處理業(yè)務(wù)邏輯(藍(lán)橋杯軟件大賽培訓(xùn)教材-Java方向)
- Java系統(tǒng)化項(xiàng)目開發(fā)教程
- Getting Started with Hazelcast(Second Edition)
- Visual FoxPro 6.0程序設(shè)計(jì)
- OpenCV 3計(jì)算機(jī)視覺:Python語言實(shí)現(xiàn)(原書第2版)
- PyQt編程快速上手
- 跟戴銘學(xué)iOS編程:理順核心知識(shí)點(diǎn)
- Machine Learning for OpenCV
- Visual Basic程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)及考試指南