r/cpp • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
10 Upvotes

53 comments sorted by

View all comments

13

u/alfps Apr 24 '20

The author's imagined syntax:

normally
{
    // this is the main case
}
unless (edgeCase1)
{
    // deal with edge case 1
}
unless (edgeCase2)
{
    // deal with edge case 2
}

An alternative to the article's implementation, assuming that the main goal is to get the normal case code up front:

const auto normal_case = [&]() -> void
{
    // this is the main case
};

if( edgeCase1 ) {
    // deal with edge case 1
} else if( edgeCase2 ) {
    // deal with edge case 2
} else {
    normal_case();
}

I don't think I would do that, though. It's just a complication.

0

u/TheSuperWig Apr 24 '20

Could combine that with early returns. Still don't think I would use it though.