[C++17]Limiting Variable Scopes to if and switch

in #coding6 years ago (edited)

Pattern

if(auto var(...); condition) /* do something */;

switch(auto var(...); var) {/* do something */}


Description

When we want to find a key in std::map, we have to make iterator to store result of find(). Then we use if statement to know iterator found what we want or not(iterator != map.end()). This iterator is used only once for the statement. It is wastage and annoying that the iterator is never used after the statement, while intellisense keeps to display the iterator.

In C++17, if and switch statement can have initializer, like for statement. After statement is done, the initialized variable is not accessible anymore. This is helpful which our code keeps tidy and makes easier to refactor.


Example

std::map<int, std::string> nameMap;

if (auto itr(nameMap.find(2)); itr != nameMap.end())

std::cout << itr->first << ": " << itr->second.c_str() << std::endl;

//itr lifespan is over after this line.

Sort:  

I believe this feature is built taking the idea from Go.

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.034
BTC 64513.75
ETH 3146.11
USDT 1.00
SBD 3.95