我在阅读一个开源代码时遇到了这个分号。我最初以为这是一个错误,但事实并非如此。
下面for循环的左括号后面的分号的作用是什么?
if (nCount > 0){
for(; nCount > 0; nCount--){
if (mBitmaplist[nCount - 1] != null){
mBitmaplist[nCount - 1].recycle();
mBitmaplist[nCount - 1] = null;
}
}
}
表示for循环中没有初始化项部分的语句
类似地,如果你想跳过for循环的增量部分,它看起来像
for( ; nCount > 0; ){
// some code
}
// which is like while loop
在JLS中这是for循环
的格式BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
你可以看到这三个都是可选的
语句for (PART1; PART2; PART3) { BODY }
的工作原理如下:
PART1;
<<TOP OF LOOP>>
if PART2 is false then go to <<END OF LOOP>>;
do the BODY;
PART3;
go to <<TOP OF LOOP>>;
<<END OF LOOP>>
如果你说for (; PART2; PART3)
,那就意味着PART1
什么也不做。(PART3
也是一样。如果你忽略了PART2
,那么什么都不会被测试,go to <<END OF LOOP>>
也不会发生。因此,到达循环结束的唯一方法是使用break
或return
或其他东西)
希望这个例子能帮助你更好地理解:
public static void main(String[] args) {
int i = 0; // you normally put this before the first semicolon in next line
for (;;) {
if (i > 5) {
break; // this "if" normally goes between the 2 semicolons
}
System.out.println("printing:" + i);
i++; // this is what you put after the second semi-colon
}
}
玩得开心,继续写!