O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required