C: why are extra semicolons OK?

前端 未结 7 857
长发绾君心
长发绾君心 2021-01-25 06:20
#include 

int main() {
    int a = -1, b = -10, c = 5;
    if (a > b)
        printf(\"Hello World\");
    else
        printf(\"Get out World\");;;;;         


        
7条回答
  •  鱼传尺愫
    2021-01-25 07:02

    Well, the ; semicolon in C is a statement terminator, which means that you cannot put it where you like, only at the end of a statement.

    The null statement (one that does nothing) is valid in C, which allow you to write things as the one you post, and things like:

    while((data = do_read(...)) != NULL); /* skip input until EOF */
    

    that should be more visible written as (a single semicolon is too small to be skipped in a quick read):

    while((data = do_read(...)) != NULL) continue;
    

    which looks better as you'll never think that the next line is inside the loop.

    By the way, if you write something like:

    if (a > b); /* <====== LOOK at this semicolon */
        printf("Hello World");;;;;;
    else
        printf("Get out World");
    

    it will not compile, as that means if a greater than b just do nothing and that's a good valid sentence in C. By contrast you'll get an error several lines later, when the compiler gets to the else token and cannot match it to an if statement (remember, when you used the ;, you finished the ifstatement)

    That also happens to occur with the group of semicolons you put after the printf("Hello World"); statement (the first semicolon terminates it, and also as the next token is not an else but a ;, also terminates the if statement).

    The statements in the example above are:

    if (a > b); /* if a greater than b do nothing */
    ; /* do nothing */
    ; /* ... */
    ; /* ... */
    ; /* ... */
    ; /* do nothing */
    else /* ERROR, else cannot begin a statement */
    ....
    

    Here, as you got a syntax error from the compiler, you cannot have a good C program so you'll not get further analysing (the compiler tries to recover and continue parsing past that point, but you can have new errors originating of the new condition, or fake errors)

提交回复
热议问题