Sandeep
Sandeep

Reputation: 7334

Why does code with multiple semicolons compile?

I am just curious to know why this is 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.

Upvotes: 4

Views: 256

Answers (5)

snemarch
snemarch

Reputation: 5018

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.

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81507

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.

Upvotes: 5

Michael Petrotta
Michael Petrotta

Reputation: 60942

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.

Upvotes: 16

kemiller2002
kemiller2002

Reputation: 115518

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

Upvotes: 0

Will A
Will A

Reputation: 25008

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.

Upvotes: 1

Related Questions