是做,而假循环共同之处? [英] Are do-while-false loops common?

查看:109
本文介绍了是做,而假循环共同之处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前阵子我换我来处理空调风格错误的方式。

A while back I switched the way I handled c style errors.

我发现了很多我的code的是这样的:

I found a lot of my code looked like this:

int errorCode = 0;

errorCode = doSomething();
if (errorCode == 0)
{
   errorCode = doSomethingElse();
}

...

if (errorCode == 0)
{
   errorCode = doSomethingElseNew();
}

但最近我一直在写这样的:

But recently I've been writing it like this:

int errorCode = 0;

do
{       
   if (doSomething() != 0) break;
   if (doSomethingElse() != 0) break;
   ...
   if (doSomethingElseNew() != 0) break;
 } while(false);

我已经看到了很多code哪里没有被执行有错误后,却一直被写在第一个样式。是否有其他人谁使用这种风格,如果你不这样做,为什么?

I've seen a lot of code where nothing gets executed after there's an error, but it has always been written in the first style. Is there anyone else who uses this style, and if you don't, why?

编辑:我只想澄清,通常这构造使用错误号否则我会赋值给 INT 才打破。此外还有通常比较code不仅仅是在一个函数调用,如果(错误== 0)条款。好点的地段想上,但。

just to clarify, usually this construct uses errno otherwise I will assign the value to an int before breaking. Also there's usually more code than just a single function call within the if (error == 0 ) clauses. Lots of good points to think on, though.

推荐答案

第二个片段只是看起来是错误的。你有效地重新发明的goto。

The second snippet just looks wrong. You're effectively re-invented goto.

任何人都读第一code风格就会立刻知道发生了什么,第二风格需要更多的检查,从而使维护困难,从长远来看,没有真正的好处。

Anyone reading the first code style will immediately know what's happening, the second style requires more examination, thus makes maintenance harder in the long run, for no real benefit.

编辑,在第二风格,你扔掉的错误code,所以你不能采取任何纠正措施或显示一条提示消息,日志等有用的东西......

Edit, in the second style, you've thrown away the error code, so you can't take any corrective action or display an informative message, log something useful etc....

这篇关于是做,而假循环共同之处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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