How can I avoid “for” loops with an “if” condition inside them with C++?

前端 未结 13 1822
滥情空心
滥情空心 2021-01-30 03:31

With almost all code I write, I am often dealing with set reduction problems on collections that ultimately end up with naive \"if\" conditions inside of them. Here\'s a simple

13条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 04:14

    One style that gets used enough to mention, but hasn't been mentioned yet, is:

    for(int i=0; i

    Advantages:

    • Doesn't change the indentation level of DoStuff(); when condition complexity increases. Logically, DoStuff(); should be at the top-level of the for loop, and it is.
    • Immediately makes it clear that the loop iterates over the SOMETHINGs of the collection, without requiring the reader to verify that there is nothing after the closing } of the if block.
    • Doesn't require any libraries or helper macros or functions.

    Disadvantages:

    • continue, like other flow control statements, gets misused in ways that lead to hard-to-follow code so much that some people are opposed to any use of them: there is a valid style of coding that some follow that avoids continue, that avoids break other than in a switch, that avoids return other than at the end of a function.

提交回复
热议问题