开发者

Why does code with multiple semicolons compile?

I am just curious to know why this is 开发者_Python百科allowed.

int i=0;;

I accidentaly typed that. But the program compiled. I noticed it after many days that I have typed ;;

After that I tried with different symbols like ~, !, : etc etc

Why is that not allowed where as first one is allowed.

Just curious to know.


You have typed an empty statement:

int i=0; // that's one statement
; // that's another

It's legal for an statement in C# to have no body.

From section 8.3 of the C# Language Specification:

An empty-statement does nothing.

empty-statement:
;
An empty statement is used when there are no operations to perform in a context where a statement is required.


The empty statement can actually be useful. Check out this interesting infinite looping example:

    for (;;)
    {
        // loops infinitely
    }

Run the following version as proof, but with break from infinity:

    int count = 0;
    for (;;)
    {
        count++;
        if (count > 10) break;
    }

    Console.WriteLine("Done");

But, if you really want to do an infinite loop, use: while (true) {} instead of for (;;) {}. The while(true) is less terse, easier to read and readily communicates the intent of looping indefinitely.


The extra ; just marks out an additional, albeit blank, 'line' of C# code. The other symbols have no meaning when they're just placed on their own.


C# (and a lot of other languages) use the semicolon to separate statements, rather than caring about line breaks. Empty statements are valid, so you can put as many semicolons as you want. It also means you can put multiple statements on one line, or split a single statement across multiple lines - the compiler won't care.


Because the semi-colon signifies the end of a statement. The others do not. You can have a blank statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜