why there is semicolon after loop while();

后端 未结 4 421
天命终不由人
天命终不由人 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:00

    The ; is just a null statement, it is a no op but it it the body of the while loop. From the draft C99 standard section 6.8.3 Expression and null statements:

    A null statement (consisting of just a semicolon) performs no operations.

    and a while statement is defined as follows from section 6.8.5 Iteration statements:

    while ( expression ) statement

    So in this case the statement of the while loop is ;.

    The main effect of the while loop is here:

    string1[i++] == string2[j++]
            ^^^             ^^^
    

    So each iteration of the loop increments i and j until the whole condition:

    string1[i++] == string2[j++] &&string1[i-1] != 0 && string2[j-1] != 0
    

    evaluates to false.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-18 11:08

    Semicolon is like empty instruction. If we don't put any instruction after while or use loop while with {} we must use semicolon to tell compiler that all we want from while loop is doing this empty instruction.

    0 讨论(0)
  • 2020-12-18 11:08

    That is called a semicolon. In programming standards, the ; signifies an end of statement, or in this case that it is a null statement. It is effectively a non operation in the body of the while loop, so it is not actually doing anything.

    0 讨论(0)
提交回复
热议问题