我可以用什么而不是休息;打破if语句? [英] what can I use instead of break; to break an if statement?

查看:82
本文介绍了我可以用什么而不是休息;打破if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

{

if(color == red)

...

if (汽车==现代)休息;

...

}

for an example
{
if( color == red )
...
if( car == hyundai ) break;
...
}

推荐答案

你拥有的唯一方式如果语句(即退出 if 语句块)使用,则打破转到。然而,这可能是丑陋设计的一个症状。
The only way you have to 'break' an if statement (that is exiting the if statement block) is using goto. However that is probably a symptom of ugly design.


如果你有一个相对较长的代码块(例如if语句的块)并且你想要突破它在几个地方,你可以使用以下结构:



If you have a code block (e.g. the block of an if-statement) that is relatively long and you want to break out of it at several places, you may use the following construct:

do {
   ... some code ...
   if (...)
       break;
   ... some more code ...
   if (...)
       break;
   ... some more code ...
} while (0);



do-block保证只执行一次,你可以通过 break



但是,请考虑这样的结构是最后的手段。最好以一种你不需要诉诸这种技巧的方式构建代码。


The do-block is guaranteed to be executed just once and you can break out of it in the usual way with break.

However, consider that such constructs are kind of a last resort. It's probably better to structure your code in a way that you don't need to resort to such "tricks".


技术上每个控制流语句都是等价的,i。即您可以重写使用一个控制流语句的任何代码,使其使用另一个控制流语句,同时获得相同的结果。并不总是一个好主意;)



在你的例子中,如果外部循环是一个循环,你可以使用继续而不是休息。但是,由于这只会导致跳转到循环的下一次迭代,您还需要记住您希望退出循环并在循环条件中检查这一事实:

Technically every control flow statement is equivalent, i. e. you can rewrite any code that uses one control flow statement in such a way that it uses another control flow statement instead, while arriving at the same result. Not that it would always be a good idea ;)

In your example, if the outer loop is a loop, you can use continue instead of break. However, as this would just lead to jump forward to the next iteration of the loop, you also need to remember the fact that you wish to exit the loop and check this in your loop condition:
bool end_of_loop = false;
...
do {
   ...
   // some code
   ...
   if (...) {
      end_of_loop = true;
      continue;
   }
   ...
   // some more code
   ...
} while (!end_of_loop);



此代码可以使用对于任何类型的循环:执行,而 ,但不是其他类型的代码块。



此外,对于 break ,它确实没有任何进步 - 无论是从可读性还是性能,所以如果你的目标是避免 goto -like命令,你可以在代码中使用 if 作为跳过代码块的其余部分:


This code will work for any kind of loop: do, for or while, but not other types of code blocks.

Also it really is no improvement over break - neither from the point of readability nor performance, so if your goal is to avoid goto-like commands, you can instead use if inside your code as a means to skip over the rest of the code block:

bool end_of_loop = false;
...
do {
   ...
   // some code
   ...
   if (...) {
      end_of_loop = true;
   }
   if (!end_of_loop) {
      ...
      // some more code
      ...
   }
} while (!end_of_loop);



这适用于任何类型的代码块,而不仅仅是循环。


This will work in any kind of code block, not just loops.


这篇关于我可以用什么而不是休息;打破if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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