0

So basically given the below code.

When action = 2; and mode = 1 Will i ever be set to 2?

I am working on a colleagues code, and it is written like this, but I thought that break would just skip the if and continue the rest of case 2. So basically the if statement is pointless.

switch(action){

   case 1: i = 1; break;

   case 2: if(mode == 1)
           {
              break;
           }

           i = 2;
           break;

   case 3: i = 3; break;

Ive rewritten this as:

 case 2: if(mode != 1)
            i = 2;
         break;

But it is not the only place, and some more complex. If im going to refactor it I need some info that I am correct.

4

4 回答 4

7

There's no such a thing as an "if loop." Break can never refer to an "if" statement.

See Wasserman's answer for a pointer to the language specification.

Also, assuming that 1 <= action <= 3, your code simplifies to:

if(! (action == 2 && mode == 1)) {
     i = action;
}
于 2012-05-28T12:10:25.060 回答
1

JLS 第 14.15 节

break 语句将控制权转移到封闭语句之外。

断句:

   break Identifieropt ;

没有标签的 break 语句试图将控制转移到最里面的封闭方法或初始化程序块的switchwhiledofor语句 (强调添加);此语句称为中断目标,然后立即正常完成。

于 2012-05-28T12:13:00.863 回答
1

如果这是您想知道的,那么您的重构是正确的。

于 2012-05-28T12:13:43.783 回答
1

if action == 2and mode == 1,i = 2不会被执行(为什么不测试呢?会比在这里问更快)。

但是您的改进无论如何都更清洁,我会使用它。

于 2012-05-28T12:13:54.120 回答