continue和break新用法

Continue和break

我们都很熟悉continue和break关键字的作用:

  • continue:跳出本次循环,继续下次循环,局部变量的值不变。

  • break:跳出循环结构,结束循环,局部变量失效。

但最近查看源码的时候发现了continue和break的另一种用法:在某段代码前用标识字符串标志,使用continue:标识字符串可以跳回这段代码之前继续执行,同理,使用break:标识字符串可以跳出到这段代码之前往下执行。区别在于continue之后在重新执行代码的时候局部变量值不变,而break之后局部变量重新初始化。

	//代码清单:
	
			//continue用法实例
			startSearchForLastChar:
		        while (true) {
		            while (i >= min && source[i] != strLastChar) {
		                i--;
		            }
		            if (i < min) {
		                return -1;
		            }
		            int j = i - 1;
		            int start = j - (targetCount - 1);
		            int k = strLastIndex - 1;
		
		            while (j > start) {
		                if (source[j--] != target[k--]) {
		                    i--;
		                    continue startSearchForLastChar;
		                }
		            }
		            return start - sourceOffset + 1;
		        }
		    }


			//break用法实例
			outer:
		        for (int k = less - 1; ++k <= great; ) {
		            long ak = a[k];
		            if (ak == pivot1) { // Move a[k] to left part
		                a[k] = a[less];
		                a[less] = ak;
		                ++less;
		            } else if (ak == pivot2) { // Move a[k] to right part
		                while (a[great] == pivot2) {
		                    if (great-- == k) {
		                        break outer;
		                    }
		                }
		                if (a[great] == pivot1) { // a[great] < pivot2
		                    a[k] = a[less];
		
		                    a[less] = pivot1;
		                    ++less;
		                } else { // pivot1 < a[great] < pivot2
		                    a[k] = a[great];
		                }
		                a[great] = ak;
		                --great;
		            }
		        }
		    }

猜你喜欢

转载自blog.csdn.net/weixin_38927996/article/details/87522158
今日推荐