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