why there is semicolon after loop while();

后端 未结 4 512
天命终不由人
天命终不由人 2020-12-18 10:54

I am reading a code of my friend an I see this:

#include 
#include 

void main()
{
    char string1[125], string2 [10];
    in         


        
4条回答
  •  长情又很酷
    2020-12-18 11:01

    Usually, in a while loop, you have initialization, a comparison check, the loop body (some processing), and the iterator (usually either an addition of an index, or a pointer traversal e.g. next), something like this:

    index = 0 // initialization
    while(index < 4) { // comparison, loop termination check
         printf('%c\n', mystring[index]); // Some processing
         index += 1; // iterate to next loop
    }
    

    Without at least the last item, you won't ever exit the loop, so normally the loop body has more than one statement in it. In this case, they use post-increments like this:

    while (string1[i++] == string2[j++]);
    

    This does the comparison (the ==) and the iteration (the post-increment ++) in the comparison statement itself, and has no body, so there's no reason to add any other statements. A blank loop body can be represented by just a semicolon.

提交回复
热议问题