Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c - Why no semicolon gives errors but too many of them don't?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...