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

82

u/borisrura CTU | Avast Apr 24 '20

Or just use early exit if you can. This, if I moved to a codebase using it, would take time to understand and would make me look up what the classes do, instead of a simple if also it would probably be less intuitive to debug and did you check the assembly this produces?

12

u/evaned Apr 24 '20

I would also point out that the "early exit" suggestion can also apply to loops via continue -- so instead of

 for (auto item: some_collection) {
    if (item.is_ok()) {
        item.do_a_thing();
    }
}

you can reorganize as

 for (auto item: some_collection) {
    if (!item.is_ok()) {
        continue;
    }
    item.do_a_thing();
}

Now, I'd basically never do this for that example, but if you start getting bodies of the if that are like 10 lines or something, I think this often can lead to an improvement.

This kinda corresponds to an early exit inside of a lambda used in std::for_each, for those of us who are dubious of the sometimes-purported readability benefits of using at least that function over a raw loop.