[英]Output of the for loop?
int main() {
int i,j,count;
count=0;
for(i=0; i<5; i++);
{
for(j=0;j<5;j++);
{
count++;
}
}
printf("%d",count);
return 0;
}
如果我們放在這里; 在 for() 之后 for 循環不運行任何東西。 那么程序執行完后count是怎么變成1的呢?
有一種情況
count++;
在只增加計數器一次的程序中。
解釋:
int main() {
int i,j,count;
count=0;
for(i=0; i<5; i++);
{ // i == 5, count == 0
for(j=0;j<5;j++);
{ // i == 5, j == 5, count == 0
count++; // i == 5, j == 5, count == 1
}
}
printf("%d",count); //i == 5, j == 5, count == 1
return 0;
}
也就是說,正如你提到的
如果我們放在這里
;
在 for() 之后 for 循環不運行任何東西。
不完全正確。 如果你把;
在循環構造之后,它表現為循環體為空,即循環體中沒有代碼。 循環仍在運行,下一個塊不被視為循環體,而是無條件流程的一部分。
不要僅僅被縮進所迷惑。 你的代碼,可以重寫為
int main(void) {
int i,j,count;
count=0;
for(i=0; i<5; i++) // ; removed
{
// no code
}
{ // just another block, not previous loop body
for(j=0;j<5;j++) // ; removed
{
// again no code
}
{ // again just another block, not previous loop body
count++;
}
}
printf("%d",count);
return 0;
}
這基本上歸結為:
int main() {
int count = 0;
{
count++;
}
printf("%d",count);
return 0;
}
我認為您的困惑可能在於將;
在for
語句之后。
for (i = 0; i < 5; i++);
和寫作一樣
for (i = 0; i < 5; i++) {
;
}
C 查看for (...)
之后的第一條語句(在本例中為;
語句),然后將其作為 for 循環的主體執行。 所以,當你寫
for (i = 0; i < 5; i++);
{
// other stuff
}
您的程序基本上會跳過 for 循環,因為它確實會;
5次。 然后, //other stuff
被執行一次,因為它不是 for 循環的一部分。 這有意義嗎?
因此,您的代碼只會增加count
一次。
一旦你忽略了for
循環,剩下的就變成了:
int main() {
int i,j,count;
count=0;
{
{
count++;
}
}
printf("%d",count);
return 0;
}
所以你可能會看到counter
增加了一次。
您的代碼如下所示,放入 ; 在兩個 for 循環的末尾。
int main() {
int i,j,count;
count=0;
for(i=0; i<5; i++);
{
//do nothing
}
for(j=0;j<5;j++);
{
//do nothing
}
count++;
printf("%d",count);
return 0;
}
兩個 for 循環都不做任何事情,之后只有一個語句是 count++,所以它增加了 count 的值。這就是它在 Output:1 中打印值的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.