Java 空的 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16428903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Empty if-statements
提问by nullptr
By "empty if-statement", I mean something like this (note the semicolon):
通过“空 if 语句”,我的意思是这样的(注意分号):
if (condition);
I'm having trouble thinking of an application for this. With a while loop you can do this:
我在考虑为此提出申请时遇到了麻烦。使用 while 循环,您可以执行以下操作:
while (callUntilReturnsFalse());
But there's no such application for an if-statement. What's more, the Java compiler doesn't issue an error or a warning when confronted with such a statement. This can lead to large and silentproblems, especially with a long and convoluted statement:
但是对于 if 语句没有这样的应用。更重要的是,Java 编译器在遇到这样的语句时不会发出错误或警告。这可能会导致大而无声的问题,尤其是在一个冗长而复杂的陈述中:
if ((functionA() && functionB(getFoo()) ||
checkForComplexCondition(arg1, arg2, getBar(getFoo())));
{
doStuff();
}
My question is: why is this allowed in Java? And, more importantly, can I enable an option to cause a warning when this happens?
我的问题是:为什么这在 Java 中是允许的?而且,更重要的是,我可以启用一个选项以在发生这种情况时发出警告吗?
(This question was asked beforewith regards to C#, which does issue a warning, but I was hoping to find a way to cause a warning with Java.)
(这个问题之前是关于 C# 的,它确实发出警告,但我希望找到一种方法来引起 Java 警告。)
采纳答案by Maroun
why is this allowed in Java?
为什么这在 Java 中是允许的?
See Java Language Specification (14.6. The Empty Statement):
An empty statement does nothing.
空语句什么也不做。
It's simply allowed and it's equivalent to (and will be translated to):
它只是被允许的,它相当于(并将被转换为):
if (condition) { }
Which means, if the condition is true, do nothing.
这意味着,如果条件为真,则什么都不做。
If you're using eclipse, you can look here, you might find something useful (I'm not sure there exists such an option for semicolon terminator):
如果您使用的是 Eclipse,您可以查看这里,您可能会发现一些有用的东西(我不确定分号终止符是否存在这样的选项):
Window→ Preferences→ Java→ Compiler→ Error/Warnings
窗口→首选项→ Java→编译器→错误/警告
EDIT
编辑
As @nullptr pointed out in his answer, there exist an IDE warning for this, you need to set warningon Empty statement.
正如@nullptr 在他的回答中指出的那样,存在一个 IDE 警告,您需要在Empty statement上设置警告。
回答by Hyman
I don't see so much danger in the possibility of an if
with an empty statement. The rationale behind it resides in the grammar of the Java language, which allows the empty statement ;
:
我没有看到if
带有空语句的可能性有多大危险。它背后的基本原理在于 Java 语言的语法,它允许使用空语句;
:
Block:
{ BlockStatements }
BlockStatements:
{ BlockStatement }
BlockStatement:
LocalVariableDeclarationStatement
ClassOrInterfaceDeclaration
[Identifier :] Statement
LocalVariableDeclarationStatement:
{ VariableModifier } Type VariableDeclarators ;
Statement:
Block
;
Identifier : Statement
StatementExpression ;
if ParExpression Statement [else Statement]
assert Expression [: Expression] ;
switch ParExpression { SwitchBlockStatementGroups }
while ParExpression Statement
do Statement while ParExpression ;
for ( ForControl ) Statement
break [Identifier] ;
continue [Identifier] ;
return [Expression] ;
throw Expression ;
synchronized ParExpression Block
try Block (Catches | [Catches] Finally)
try ResourceSpecification Block [Catches] [Finally]
Mind that this is true for almost all imperative languages.
请注意,几乎所有命令式语言都是如此。
I mean it can be dangerous and difficult to find as every other empty body in case you forgot any implementation, certainly nothing I would lose the sleep for. In a long and convoluted statement you could get problems because of a ( )
closing the wrong pair of expressions or even for thinking your condition wrong (especially with many &&
and ||
).
我的意思是,如果您忘记任何实施,它可能很危险且难以找到,因为其他所有空的身体都不会因为我而失眠。在冗长而复杂的语句中,您可能会因为( )
关闭错误的表达式对或什至认为您的条件错误(尤其是 many&&
和||
)而遇到问题。
回答by David Cummins
I'm mostly a C# developer, although I have a little Java background. But I think my answer applies to both. I suspect it's not an intentional feature, but more of an emergent feature. The grammar of the language goes (roughly)
我主要是 C# 开发人员,虽然我有一点 Java 背景。但我认为我的回答适用于两者。我怀疑这不是故意的功能,而是更多的紧急功能。语言的语法(大致)
if (*condition*)
*statement*
Unfortunately the below are both valid statements (I checked, you can drop as many into C# as you like and the compiler doesn't complain):
不幸的是,以下都是有效的语句(我检查过,您可以根据需要将任意数量放入 C# 中,并且编译器不会抱怨):
;
{
}
Therefore the construct that you highlighted is allowed.
因此,您突出显示的构造是允许的。
回答by user1445967
In the statement
在声明中
if (eval) { //pseudo-code
}
Sometimes data is actually changed in evaluation of (eval). For example, in
有时数据实际上在评估(eval)时发生了变化。例如,在
while (someIterator.next()) {
}
Calling next() actually changes the state of the someIterator object.
调用 next() 实际上改变了 someIterator 对象的状态。
And of course there is the classic example that usually happens from a typo (and is not recommended)
当然还有一个经典的例子,通常是因为打字错误(不推荐)
int x;
if (x = getNumberOfWidgets() > 5) {
}
Conventional wisdom advises against coding this way, as it is harder to tell what is going on. However, the statements are legal and so that is one reason why such an 'if' statement is allowed.
传统智慧建议不要以这种方式进行编码,因为很难判断发生了什么。但是,这些语句是合法的,因此这就是允许使用“if”语句的原因之一。
回答by aaronman
I believe that they left it in because it can increase code readability. Even if nothing should be done for a case you may still want to let people know that the case is important.
我相信他们保留它是因为它可以提高代码的可读性。即使对于一个案例不应该做任何事情,您可能仍然想让人们知道这个案例很重要。
回答by aran
Most Java compilers make no optimization of code at all. They delegate this work during runtime to the Java Runtime Environment. The JVM verifies the code before it's executed, butthis verification consists (mainly) of three checks:
大多数 Java 编译器根本不优化代码。他们在运行时将这项工作委托给 Java 运行时环境。JVM 在代码执行之前对其进行验证,但这种验证(主要)包括三个检查:
- Branches in validpositions(not the same as correct) .
- Data is always initialized and references are always type-safe
- Access to private data is controlled.
- 有效位置的分支(与正确位置不同)。
- 数据总是被初始化并且引用总是类型安全的
- 对私人数据的访问受到控制。
So, your if
statement may be wrong, but it's still valid. As valid as
所以,你的if
陈述可能是错误的,但它仍然有效。一样有效
if (a==a)
回答by user207421
The condition could be a function call with side effects. It wouldn't be correct to treat it as an error or warning.
条件可能是具有副作用的函数调用。将其视为错误或警告是不正确的。
回答by Curt
There's one construct that I use fairly frequently which the "null statement" makes clearer and easier to understand. Here's an example:
我经常使用一种结构,“空语句”使这种结构更清晰、更易于理解。下面是一个例子:
for (int i=0; i < argc; i++)
{
if (argv[i]=="left")
hpos++;
else if (argv[i]=="right")
hpos--;
else if (argv[i]=="up")
;
else if (arv[i]=="down")
;
else fprintf(stderr, "Unknown option \"%s\n".", argv[i]);
}
In this case, I still want to check for the existenceof certain options, while only executing code for someof them. In this case, using the null statement, as above, makes the function and structure of the code more readable and comprehensible to the next guy who has to come along and maintain it.
在这种情况下,我仍然想检查某些选项是否存在,同时只执行其中一些选项的代码。在这种情况下,使用 null 语句,如上所述,使代码的功能和结构对于下一个必须出现并维护它的人来说更具可读性和理解性。
There are certainly ways to restructure this code to not require the null statement. But I don't believe that its intention will be as clear as in the code snippet.
当然有一些方法可以重构此代码以不需要 null 语句。但我不相信它的意图会像代码片段中那样清晰。
回答by nullptr
I found a warning for this in Eclipse as Empty statement
:
我在 Eclipse 中发现了一个警告Empty statement
:
Thanks to Maroun Maroun for putting me on the right track.
感谢 Maroun Maroun 让我走上正轨。
回答by OldCurmudgeon
I don't think this is truly relevant to the intent of the question but I think it should be stated as it is relevant to the essence of the question.
我不认为这与问题的意图真正相关,但我认为应该说明它与问题的本质相关。
There isan effect of an:
这里是一个效果:
if(variable);
if the variable is volatile
. It''s effect is to cause a memory barrier to be honoured between the current thread and any other threads accessing the variable.
如果变量是volatile
. 它的作用是在当前线程和访问该变量的任何其他线程之间引起内存屏障。
public volatile variable;
....
if(variable);
See herefor a more detailed discussion.
有关更详细的讨论,请参见此处。
I cannot imagine any real value to putting this kind of statement in your code but I felt it important to note that there is a real effect to this statement in this very specific situation.
我无法想象将这种语句放入您的代码中的任何实际价值,但我觉得重要的是要注意在这种非常特殊的情况下该语句会产生实际影响。