It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center




已关闭8年。




Eclipse不断声明最后一个elseif和else是死代码,但我不明白。
if (img0 != null && img1 != null) {
    code;

} else if (img0 != null) {
    code;
} else if (img1 != null) {
    code;
} else {
    code;
}

我的理由是这样的:
  • 如果bote img0和img1不为null,则if评估为true
  • 如果评估为假,则
  • img0为空或
  • img1为空或
  • img0和img1均为空。
  • 如果img0不为空,则第一个elseif评估为true,如果评估为false,则img1可能不为null或img0和img1都为空

  • 我想念的是什么,“死亡”在哪里?

    提前致谢。

    最佳答案

    看一下这两种方式对代码的使用:-

    方式1:-

    public static void main(String[] args)
    {
        String img0 = null;
        String img1 = "Asdf";
    
        /** Currently there is no code here, that can modify the value of
            `img0` and `img1` and Compiler is sure about that.
        **/
    
        /** So, it's sure that the below conditions will always execute in a
            certain execution order. And hence it will show `Dead Code` warning in
            either of the blocks depending upon the values.
        **/
    
        if (img0 != null && img1 != null) {
           // code;
    
        } else if (img0 != null) {
            //code;
    
        } else if (img1 != null) {
            //code;
        } else {
           // code;
        }
    }
    

    在这种情况下,您肯定会在一个或另一个块上收到dead code警告,因为您是在块之前设置值,并且编译器确保这些值在这些块的初始化和执行之间不会改变。

    方式2:-
    public static void main(String[] args)
    {
        String img0 = null;
        String img1 = "Asdf";
    
        show(img0, img1);
    }
    
    public static void show(String img0, String img1) {
    
        /** Now here, compiler cannot decide on the execution order,
            as `img0` and `img1` can have any values depending upon where
            this method was called from. And hence it cannot give dead code warning.
        **/
    
        if (img0 != null && img1 != null) {
           // code;
    
        } else if (img0 != null) {
            //code;
    
        } else if (img1 != null) {
            //code;
        } else {
           // code;
        }
    }
    

    现在,在这种情况下,您将不会收到dead code警告,因为不确定编译器是从哪里调用show方法的。 img0img1的值可以是方法内部的任何值。
  • 如果两个都是null,则将执行最后一个else
  • 如果是one of them is null,则将执行else if之一。
  • 而且,如果它们都不是null,那么将执行您的if


  • 注意:-

    如果需要,可以将Eclipse配置为在某些情况下不显示warnings-Unneccessary elseUnused Imports等。

    关于java - 为什么Eclipse提示死代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13562961/

    10-10 10:31