Why no semicolon gives errors but too many of them

2019-01-20 13:47发布

Consider this C code:

#include <stdio.h>;

int main(void) {
    puts("Hello, world!");; ;
    ;
    return 0; ;
    ; ;
};

Here I've put semicolons almost everywhere possible. Just for fun. But surprisingly it worked! I got a warning about the semicolon after include but other absolutely wrong semicolons worked. If I forget to put a semicolon after puts, I'll get the following error

error: expected ';' before 'return'


Why don't lots of wrong and useless semicolons cause errors? To my mind they should be treated as syntax errors.

标签: c semicolon
5条回答
女痞
2楼-- · 2019-01-20 13:53

A single semicolon constructs a null statement. It's not only legal, it's also useful in some cases, for instance, a while/ for loop that doesn't need a real body. An example:

while (*s++ = *t++)
    ;

C11 6.8.3 Expression and null statements

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


The only syntax error is this line:

#include <stdio.h>;
查看更多
贼婆χ
3楼-- · 2019-01-20 13:54

Why should an empty statement be an error? It is not.

查看更多
\"骚年 ilove
4楼-- · 2019-01-20 14:09

The ; is a statement delimiter in C as mentioned in the above answer. Rahul's answer is perfectly correct, just that you can see this answer to a question which asks why a statement in C ends with a semicolon. Thus, when you understand why a semicolon is used, you will understand what happens when you put too many semicolons.

查看更多
仙女界的扛把子
5楼-- · 2019-01-20 14:10

semicolon means end of a statement whether it is empty or not. No semicolon means you have not closed/ end last statement but started a new one which gives error. too many semicolon indicates end of blank statement each. So, it does not give error

查看更多
相关推荐>>
6楼-- · 2019-01-20 14:13

The ; (statement delimiter) is always used to specify that particular statement is ended. There after next statement is executed.

If you dont put delimeter, then it will consider the next statement with the current statement and execute. And that gives a syntatic error.

But in other case when we put multiple delimeters eg:

int a;;;;;

In that case we have 5 statements, in which int a is first statement and next four statements are null statements that will be removed by compiler at during compilation.

See some interesting cases for this question:

int main()
{
    int a=0 ;,;
    return 0;
}

when we change above programj it it still works:

int main()
{
    int a=0 ,; /*change done*/
    return 0;
}
查看更多
登录 后发表回答