开发者

An unusual for loop statement [closed]

开发者 https://www.devze.com 2023-03-09 20:49 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years 开发者_如何学Cago.

In C and C# this snippet:

int ii;
for(ii=1;ii<5;ii++);
printf("ii = %d",ii);

prints out ii = 5 whereas this snippet (notice the <=):

int ii;
for(ii=1;ii<=5;ii++);
printf("ii = %d",ii);

prints out ii = 6.

Can you explain what is going on here? How come the for loop ends with a semicolon?


The body of your for loop is empty:

int ii;
for(ii=1;ii<5;ii++);
//                 ↑ body of the for loop
printf("ii = %d",ii);

The code sets ii to 1, then increments ii until it's 5 without doing anything in the for loop body, and finally prints ii.

If you want to print the number 1 to 4 then you should place the printf call in the for loop body:

int ii;
for(ii=1;ii<5;ii++) {
    printf("ii = %d",ii);
}


for (i = 0; i < 5; i++);

Iterates from 0 to 4 and with each iteration it does nothing. This nothing is the empty statement which is the semicolon.

This can make sense as e.g. here:

for (i = 0; i < 5; printf ("%d", i++) );


Since the for loops contains an empty statement (semicolon at the end), the value of ii is the value that causes the loop to exit. So when ii<5 is not true (because ii is 5) you see 5 output.


Remember that the increment portion of the loop declaration happens at the end of the loop, so the output is as expected - in the first example, the loop stops after ii becomes 5 (the loop body, which is empty, is executed with ii being 0 to 4).

The (empty) body of the second loop executes six times (from 0 to 5), and stops when ii becomes 6.


With your codes, getting the output 6 is correct. Here is the flow: Your 'ii' is incremented to 5 and 6 respectively (to first and 2nd loop). Because you are looping the for loop without 'the need' to execute the body

for(ii=1;ii<5;ii++); # the semicolon means you are looping it without the need to execute the body, which means it is looping without doing anything except incrementing the counter.

for (... ) { // body }

without semicolo if you have 'the need' to execute the body.


Remove the semicolon after the for, When expressing a for loop without {} it will execute code in a loop after the statement until it finds a ; and in your case the for loop is not finding a statement to execute. Remove the semicolon after the for and your next line of code , the print statement will get executed.

0

精彩评论

暂无评论...
验证码 换一张
取 消