- 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!
推薦閱讀
- Data Visualization with D3 4.x Cookbook(Second Edition)
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門寶典
- 程序設(shè)計(jì)與實(shí)踐(VB.NET)
- R語言數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南
- Full-Stack React Projects
- Learning JavaScript Data Structures and Algorithms
- Visual Basic程序設(shè)計(jì)
- Angular開發(fā)入門與實(shí)戰(zhàn)
- Python High Performance Programming
- Python Essentials
- Python 3 數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- INSTANT EaselJS Starter
- MATLAB計(jì)算機(jī)視覺實(shí)戰(zhàn)
- Mastering VMware vSphere Storage
- Flutter for Beginners