Semicolon At End of 'If' Statement

Semicolon at end of 'if' statement

Why does it happen?

Java Language Specification says that:

The Empty Statement

An empty statement does nothing.

EmptyStatement:
;

Execution of an empty statement always completes normally

It essentially means that you want to execute empty statement if a==b

if(a == b);

What should you do:

There are two main solutions to this problem:

  1. You can avoid problems with empty statement by using code formatter
    and surrounding stuff inside if with { and }. By doing this
    Your empty statement will be much more readable.

    if(a == b){
    ;
    }
  2. You can also check tools used for static code analysis such as:

    Sample Image

    • Findbugs
    • Checkstyle
    • Pmd

    They can instantly highlight problems such as this one.

I would recommend to combine both solutions.

What happens when if statement is ended with a semi colon

The if statement has nothing to do with the following block:

if (i == 10);

This is a valid statement as ; denotes an empty statement: if (i == 10) then do nothing.

{
System.out.println("It is here");
break;
}

This is a valid code block. It is syntactically correct although it does not help a lot in this case. This block will be executed in all cases and is not affected by the if statement above.

Why are semicolons not used after if/else statements?

  • Semicolon is used to end ONE statement
  • { and } begin and close a group of statements

Basically, an if-else must be followed by either a statement or a group of statements.

if-else followed by a statement:

if (condition) statement;
if (condition); // followed by a statement (an empty statement)

if-else followed by group of statements:

if (condition) {
statement;
statement;
}

if (condition) {
// followed by a group of statements of zero length
}

if-else must end with a ; if it is followed by a single statement. if-else does not end with a ; when followed by a group of statements because ; is used to end a single statement, and is not used for ending a group of statements.

Semicolon at the ends of if-statements and functions in C

They do nothing. They're a sign of someone who doesn't understand the language terribly well, I suspect.

If this is source code you notionally "own", I would remove the code and try to have a gentle chat with the person who wrote it.

Why do some people put a semicolon after an if condition in shell scripts?

if [ $a == $b ]; then
echo "a == b"
fi

You can use a semicolon, or you can write then on a separate line. Either one is allowed.

if [ $a == $b ]
then
echo "a == b"
fi

Having neither a ; nor a newline is a syntax error.

$ if [ $a == $b ] then
> echo "a == b"
> fi
bash: syntax error near unexpected token `fi'

As for [ vs [[, see:

  • What's the difference between [ and [[ in Bash?

Use of semicolons with if/else and try/finally blocks

This is documented behavior:

Declarations and Statements (Delphi): Compound Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

begin
Z := X;
X := Y;
X := Y;
end;

The last semicolon before end is optional. So this could have been written as:

begin
Z := X;
X := Y;
Y := Z
end;

And also:

Delphi's Object Pascal Style Guide: Statements

Statements are one or more lines of code followed by a semicolon. Simple statements have one semicolon, while compound statements have more than one semicolon and therefore consist of multiple simple statements.

Here is a simple statement:

A := B;

If you need to wrap the simple statement, indent the second line two spaces in from the previous line. Here is a compound, or structured, statement:

begin
B := C;
A := B;
end;

Compound Statements always end with a semicolon, unless they immediately precede an end keyword, in which case the semicolon is optional but recommended by this style guide.

An "end keyword" in your example would include except and finally.

No Semicolons after if/else statement in Function (Javascript)? What gives?

Semicolons come after if or else in JavaScript. They would belong after statements inside if or else blocks but they are technically optional.

if blocks start with if and contain a statement block which is either one expression or { + one or more expressions + }. else blocks work the same way.

Thus, all of these are equivelent:

if console.log("foo")

if console.log("foo");

if
console.log("foo")

if
console.log;

if { console.log("foo") }

if { console.log("foo"); }

if {
console.log("foo")
}

if {
console.log("foo");
}

else blocks work the same way.


For what it is worth, you should always include semicolons in JavaScript (where appropriate). They are optional but every JavaScript code guideline I've ever seen tells you to use them.

Why do java if statement fail when it ends in semicolon

This semicolon ends a statement (an empty one), so your code is translated by the compiler to something like this:

if(name != null && value != null)
{
//nothing here
}
{
System.out.println("Values not null");
}

In other words, if if expression is true, it executes empty block of code. Then no matter whether if was true or not, the runtime proceeds and runs the block containing System.out. Empty statement is still a statement, so the compiler accepts your code.

Another place where such a mistake can happen:

for(int i = 0; i < 10; ++i);
{
System.out.println("Y U always run once?");
}

or even worse (infinite loop):

boolean stop = false;
while(!stop);
{
//...
stop = true;
}

It took me hours to discover what the issue was

Good IDE should immediately warn you about such statement as it's probably never correct (like if(x = 7) in some languages).

What does a semi colon do after a conditional block in C#?

This is a simple question with a simple answer, but I just wanted to add something relevant. Often people understand that it does nothing and particularly for the case that you presented, the semi-colon is an unnecessary line termination.

But what is the rationale behind it ?

Actually, those empty statements are allowed for statement like these:

 // Use an empty statement as the body of the while-loop.
while (Method())
;

I agree that it does nothing. But it can help certain loops conform to the syntactic requirements of the language and I think this is what people should understand from it. As other said, I agree you can remove it, I just wanted to underline why C# allows it.

Further clarification

An empty statement is used when you don't need to perform an operation where a statement is required. It simply transfers control to the end point of the statement. It has no effect at all, it is pure syntactic sugar.

As stated by @PaulF, in the example above, you could use an empty block ({}) instead. It would be totally valid and have the same effect.

Again, it all comes down to style. You don't need it, but it can certainly help you conform to whatever rules of your coding environments.

Common use-cases (where one could see empty statements)

  • While loop with empty body (same case that I underlined above)

    void ProcessMessages()
    {
    while (ProcessMessage())
    ; // Statement needed here.
    }
  • goto statements (rarely use but still valid)

    void F()
    {
    //...
    if (done) goto exit;
    //...
    exit:
    ; // Statement needed here.
    }

    From MSDN

  • Class declaration (Props to @EricLippert for bringing this one)

    class SomeClass
    {
    ...
    };

Note that in this case, as stated by @EricLippert in the comments section, this is simply a courtesy to C++ programmers who are used to typing semis after classes; C++ requires this.

Even though the general use of empty statements is debatable mainly because of the confusion they can bring, in my opinion, syntactically speaking they have a place in C#. We must not forget that C# is an increment of C++ (which mostly explain the # aka. four "+" symbols in a two-by-two grid) and for historical reasons, allowing empty statements was facilitating the transition.



Related Topics



Leave a reply



Submit