简体   繁体   English

交换if语句

[英]Swap if-statements

I am working on code minimization and enhancement. 我正致力于代码最小化和增强。 My question is: is it possible to swap the if statements above without destroying the logic of the code? 我的问题是:是否可以交换上面的if语句而不破坏代码的逻辑?

    int c1 = Integer.parseInt(args[0]) ;
    int c2 = Integer.parseInt(args[1]) ;
    int c3 = Integer.parseInt(args[2]) ;

    if (c2-c1==0)
      if ( c1 != c3 )

Since between the both if statments are no operations that write the variables I would say yes but I am not sure. 因为两者之间的if语句都不是写变量的操作,我会说是,但我不确定。

Any ideas? 有任何想法吗?

I don't really see why you want (c2 - c1 == 0) instead of c1 == c2 我真的不明白你为什么要(c2 - c1 == 0)而不是c1 == c2

why not go the 为什么不去

if ((c1 == c2) && (c1 != c3)){
  do_stuff();
}

or 要么

if ((c1 != c3) && (c1 == c2)){
  do_stuff();
}

route 路线

As a note, there is no penalty or advantage in switching c1 for c2 anywhere. 作为一个注释,在任何地方切换c1 c2都没有任何惩罚或优势。 Of the above, putting the most likely to fail condition first is slightly more efficient, because the second condition will not be evaluated if the first one fails. 在上述情况中,首先放置最可能失败的条件稍微更有效,因为如果第一个条件失败则不会评估第二个条件。

Also note, this is a micro optimisation, you should never be considering for speed. 还要注意,这是一个微优化,你永远不应该考虑速度。

Third note, if your program doesn't do anything else, and exits if this condition doesn't hold, and you really do want to micro-optimise (which you don't) I suggest not parsing the arguments before you know they are needed. 第三个注意事项,如果你的程序没有做任何其他事情,并且如果这个条件不成立则退出,并且你确实想要微优化(你不这样做)我建议你先知道它们之前没有解析参数需要。 if c1 will be unequal to c2 most of the time, then you can wait with parsing c3 until you know you have to check against it. 如果c1大部分时间都不等于c2,那么你可以等到解析c3,直到你知道你必须检查它。 This is strictly theory. 这是严格的理论。 Don't do this in practice as it will make your code that much harder to read. 不要在实践中这样做,因为它会使你的代码更难阅读。 It's much clearer to process all the commandline vars to something sensible as soon as you can. 尽可能快地将所有命令行变量处理为合理的事情要清楚得多。

int c1 = Integer.parseInt(args[0]) ;
int c2 = Integer.parseInt(args[1]) ;
int c3 = Integer.parseInt(args[2]) ;

if (c2 == c1 && c1 != c3 ) {
   ...
}

Yes. 是。 You can also write if ((c2-c1==0) && (c1 != c3)) . 你也可以写if ((c2-c1==0) && (c1 != c3))

If you mean 如果你的意思是

if ((c1 != c3) && (c2-c1==0))

and you do not plan to do something special only if c2-c1==0 then yes. 如果c2-c1==0那么你不打算做一些特别的事情。

If there are no else blocks involved, then I suggest you to write it as: 如果没有涉及其他块,那么我建议你把它写成:

if (c2-c1==0 && c1 != c3 )

or, if you want to swap them, 或者,如果你想交换它们,

if (c1 != c3 && c2-c1==0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM