Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:
if(a == b); // Do stuff
Which basically means that the stuff will be done whether a
equals b
or not, and the if
statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?
Do not place a semicolon on the same line as an if, for, or while statement. Do not use a semicolon on the same line as an if , for , or while statement because it typically indicates programmer error and can result in unexpected behavior.
Control statements ( if , do , while , switch , etc.) do not need a semicolon after them, except for do ...
An IF statement is executed based on the occurrence of a certain condition. IF statements must begin with the keyword IF and terminate with the keyword END. Components within IF statements can be connected with the keywords AND or OR.
It's the semicolon! if you put a semicolon directly after the condition in an if statement, Java thinks it's finished with the body of the statement. The indentation of the next line, which is so important to human readers, is ignored by Java.
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);
There are two main solutions to this problem:
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){ ; }
You can also check tools used for static code analysis such as:
They can instantly highlight problems such as this one.
I would recommend to combine both solutions.
Is there any situation in which this would be useful?
Useful? As in "makes your code cleaner, clearer, faster, more maintainable"? Not at all. This is most likely poor, confusing code.
But it's not necessarily benign. Such a statement can perform actions and/or alter state due to methods which cause side effects, and optionally evaluate those methods due to short-circuiting of operators.
if( a() && b() );
Here, a()
or b()
may do something, and b()
will only execute if a()
is true.
As to why, I think the answer is simply that it would be worse to deviate from defined, expected behavior (e.g. statements like while(reader.read());
) than the alternative of developers writing bad code.
Writing bad code is always possible. And just to reiterate, this would be bad code in almost any case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With