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

in coding •  7 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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

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