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.
精彩评论