Significance of do{} while(0) [duplicate]

旧街凉风 提交于 2019-12-12 15:17:59

问题


What is the significance of do while loop when the condition inside the while loop is 0 i.e. always false.

do
{

//some code implementation.

}while(0);

I have seen at many places this is being used. What is its importance, Cant we just omit the do while(0). as both ways code will be executed only once.

It is not a duplicate as i asked about use of while(0) condition specifically not general do-while loop.


回答1:


It can be used to leave a certain scope of code at any point without leaving the function. Consider:

do
{
  beginAtomicOperationSequence();

  ret = doSomething();
  if (ret < 0) break;

  ret = doSomething2();
  if (ret < 0) break;

} while(0);

if (ret < 0) {
  switch (ret) {
   //handle error
  }
  rollbackAboveOperations();
} else {
  commitAboveOperations();
}

There are some cases in which I would say that this is acceptable, particularly if one needs to make a sequence of operations which are to be considered atomic. Like in the example above.




回答2:


It ensures the macro always behaves the same, regardless of how semicolons and curly-brackets are used in the invoking code.

For more details refer to this




回答3:


The do { } while(0) construct in that context, is an obfuscated way to write goto's without actually writing it out. It is used by cargo cult programmers who somewhere read that gotos are bad but didn't understand why.

Here the example of Dariusz' answer rewritten with a proper goto and a meaningfull label.

  beginAtomicOperationSequence();

  ret = doSomething();
  if (ret < 0) goto handle_error;

  ret = doSomething2();
  if (ret < 0) goto handle_error;

  ...

handle_error:
  if (ret < 0) {
    switch (ret) {
    //handle error
    }
    rollbackAboveOperations();
  } else {
    commitAboveOperations();
  }

As can be seen it is shorter and completely obvious. That you even had to ask for the purpose of that construct shows that it is a bad idea.

I am vehement in my answer, because I have a colleague who uses and abuses it in our project and I haven't found 1 redeaming value to it. It gets even more annoying when you add some real loops in the mix. Then the fun starts to find where the break and continue will lead you to.

EDIT: Here a link to Linus Torvald's rant about the subject of goto. http://kerneltrap.org/node/553/2131



来源:https://stackoverflow.com/questions/16397961/significance-of-do-while0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!