Will the Compiler Optimize this out

后端 未结 7 1340
悲&欢浪女
悲&欢浪女 2020-12-09 11:27

Say I have something like this in a C Code. I know you can use a #define instead, to make the compiler not compile it, but just out of curiosity I\'m asking if

相关标签:
7条回答
  • 2020-12-09 12:06

    Instead of asking such simple questions (where the only correct answer is "Try it out with your compiler") - why not just try it?

    public class Test {
        public static void main(String[] args) {
            if (true) {
                System.out.println("Yep");
            }
            boolean var = false;
            if (var) {
                System.out.println("Nope");
            }
            final boolean var2 = false;
            if (var2) {
                System.out.println("Nope");
            }
        }
    }
    
    javac .\Test.java 
    javap -c Test
    Compiled from "Test.java"
    public class Test {
      public Test();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return
    
      public static void main(java.lang.String[]);
        Code:
           0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
           3: ldc           #3                  // String Yep
           5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
           8: iconst_0
           9: istore_1
          10: iload_1
          11: ifeq          22
          14: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          17: ldc           #3                  // String Yep
          19: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
          22: return
    }
    

    You don't need to know much about java/c# bytecode or assembly to be able to understand what's going on. And now go and try the same for C#..

    0 讨论(0)
提交回复
热议问题