@@ -12703,17 +12703,62 @@ consider `gsl::finally()` as a cleaner and more reliable alternative to `goto ex
12703
12703
12704
12704
##### Example
12705
12705
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
+ }
12707
12716
12708
12717
##### Alternative
12709
12718
12710
12719
Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
12711
12720
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
+ }
12713
12747
12714
12748
Often, a loop that uses `continue` can equivalently and as clearly be expressed by an `if`-statement.
12715
12749
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
+ }
12717
12762
12718
12763
##### Note
12719
12764
@@ -12722,7 +12767,7 @@ If you really need to break out a loop, a `break` is typically better than alter
12722
12767
12723
12768
##### Enforcement
12724
12769
12725
- ???
12770
+ Flag any use of `break` and `continue` inside a loop.
12726
12771
12727
12772
### <a name="Res-break"></a>ES.78: Don't rely on implicit fallthrough in `switch` statements
12728
12773
0 commit comments