@@ -12703,17 +12703,62 @@ consider `gsl::finally()` as a cleaner and more reliable alternative to `goto ex
1270312703
1270412704##### Example
1270512705
12706- ???
12706+ switch(x){
12707+ case 1 :
12708+ while(/* some condition */){
12709+ //...
12710+ break;
12711+ } //Oops! break switch or break while intended?
12712+ case 2 :
12713+ //...
12714+ break;
12715+ }
1270712716
1270812717##### Alternative
1270912718
1271012719Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
1271112720
12712- ???
12721+ //BAD: break inside loop
12722+ void use1(){
12723+ std::vector<T> vec = {/* initialized with some values */};
12724+ T value;
12725+ for(const T item : vec){
12726+ if(/* some condition*/){
12727+ value = item;
12728+ break;
12729+ }
12730+ }
12731+ /* then do something with value */
12732+ }
12733+
12734+ //GOOD: create a function and return inside loop
12735+ T search(const std::vector<T> &vec){
12736+ for(const T &item : vec){
12737+ if(/* some condition*/) return item;
12738+ }
12739+ return T(); //default value
12740+ }
12741+
12742+ void use2(){
12743+ std::vector<T> vec = {/* initialized with some values */};
12744+ T value = search(vec);
12745+ /* then do something with value */
12746+ }
1271312747
1271412748Often, a loop that uses `continue` can equivalently and as clearly be expressed by an `if`-statement.
1271512749
12716- ???
12750+ for(int item : vec){ //BAD
12751+ if(item%2 == 0) continue;
12752+ if(item == 5) continue;
12753+ if(item > 10) continue;
12754+ /* do something with item */
12755+ }
12756+
12757+ for(int item : vec){ //GOOD
12758+ if(item%2 != 0 && item != 5 && item <= 10){
12759+ /* do something with item */
12760+ }
12761+ }
1271712762
1271812763##### Note
1271912764
@@ -12722,7 +12767,7 @@ If you really need to break out a loop, a `break` is typically better than alter
1272212767
1272312768##### Enforcement
1272412769
12725- ???
12770+ Flag any use of `break` and `continue` inside a loop.
1272612771
1272712772### <a name="Res-break"></a>ES.78: Don't rely on implicit fallthrough in `switch` statements
1272812773
0 commit comments