Java:不是声明

标签 java semantics

我想这更像是一个关于语言理论的问题,而不是其他任何问题。为什么 main 中的第一个语句是合法的,而第二个不是?他们评估的不是同一件事吗?

public class Main {
        public static void main(String[] args) {
                foo();
                0;
        }
        public static int foo(){
                return 0;
        }
}

最佳答案

Java 限制了所谓的“表达式语句”中允许的表达式类型。只允许具有潜在副作用的有意义的表达式。它不允许语义上无意义的语句,如 0;a + b;。它们只是被排除在语言语法之外。

foo() 这样的函数调用可以而且通常确实有副作用,所以它不是无意义的语句。编译器不会深入检查 foo() 的主体来检查它是否真的做了任何事情。调用函数可能有副作用,因此它在语法上是有效的。

这反射(reflect)了 C/C++ 和 Java 之间的哲学差异。 Java 禁止导致死代码或无意义代码的各种构造。

return;
foo();    // unreachable statement

C 和 C++ 对这一切都相对自由放任。想写什么就写什么;他们没有时间照顾你。


引自Java Language Specification, §14.8 Expression Statements :

Certain kinds of expressions may be used as statements by following them with semicolons.

ExpressionStatement:
    StatementExpression ;

StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.

Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a "cast to void" - void is not a type - so the traditional C trick of writing an expression statement such as:

(void)... ;  // incorrect!

does not work. On the other hand, the Java programming language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.26) or a local variable declaration statement (§14.4) can be used instead.

关于Java:不是声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16599183/

相关文章:

java - JDBC for mysql 重复查询性能很慢

java - BigDecimal compareTo() 线程安全

c# - 不变性/只读语义(特别是 C# IReadOnlyCollection<T>)

java - 根据调查构建人类可读的句子

logic - 使用一阶逻辑描述电影(实体和属性)

java - 使用子字符串拆分字符串

java - Eclipse 内容协助不显示方法描述

css - 没有 float 元素的两列布局?

java - RenderScript 模糊覆盖原始位图

c++ - move 语义只是一个浅拷贝并将其他指针设置为空吗?