将编译器优化了这一点 [英] Will the Compiler Optimize this out

查看:95
本文介绍了将编译器优化了这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有在C code这样的事情。我知道你可以使用的#define 来代替,使编译器不会编译它,而只是出于好奇,我问如果编译器也将弄清楚这件事的。

我觉得这是即使Java编译器更重要,因为它不支持的#define

  const int的条件= 0;
........
//将编译器编译呢?
IF(条件)
{}
.......


在Java中

解决方案

,里面的code。如果甚至不会编译code的一部分。它必须编译,但它不会被写入编译后的字节code。它实际上是依赖于编译器,但我不知道,不优化它的编译器。该规则在的JLS :


  

这是优化编译器可能会意识到语句x = 3;永不
  执行,并且可以选择忽略code从该声明
  生成的类文件,但语句x = 3;不被视为
  在这里指定的技术意义上的无法访问。


  
  

此不同治疗的基本原理是让程序员
  界定标志变量,如:

 静态最终布尔DEBUG = FALSE;


  
  

然后写code,如:

 如果(调试){X = 3; }


  
  

的想法是,它应该可能改变调试的值
  从假到真或从真到假,然后编译code
  正确地并无其他变动的程序文本。


不知道关于C。

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 the compiler will also figure this thing out.

I think this is even more important for Java Compiler as it does not support #define.

const int CONDITION = 0;
........
// Will the compiler compile this?
if ( CONDITION )
{

}
.......

解决方案

in Java, the code inside the if won't even be part of the compiled code. It must compile, but it won't be written to the compiled bytecode. It actually depends on the compiler, but I don't know of a compiler that doesn't optimize it. the rules are defined in the JLS:

An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

Don't know about C.

这篇关于将编译器优化了这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆