什么是更好的方式来避免do-while(0); hack在C ++? [英] What are some better ways to avoid the do-while(0); hack in C++?

查看:150
本文介绍了什么是更好的方式来避免do-while(0); hack在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码流如下:

if(check())
{
  ...
  ...
  if(check())
  {
    ...
    ...
    if(check())
    {
      ...
      ...
    }
  }
}

我通常看到这个工作是为了避免上面的乱码流:

I have generally seen this work around to avoid the above messy code flow:

do {
    if(!check()) break;
    ...
    ...
    if(!check()) break;
    ...
    ...
    if(!check()) break;
    ...
    ...
} while(0);

什么是更好的方法,避免这种工作/ hack, (行业级)代码?

What are some better ways that avoid this work-around/hack so that it becomes a higher-level (industry level) code?

欢迎任何建议。

推荐答案

在函数中隔离这些决定并使用 return s而不是 break s。虽然所有这些检查对应于与函数相同的抽象级别,这是相当合乎逻辑的方法。

It is considered acceptable practice to isolate these decisions in a function and use returns instead of breaks. While all these checks correspond to the same level of abstraction as of the function, it is quite logical approach.

例如:

void foo(...)
{
   if (!condition)
   {
      return;
   }
   ...
   if (!other condition)
   {
      return;
   }
   ...
   if (!another condition)
   {
      return;
   }
   ... 
   if (!yet another condition)
   {
      return;
   }
   ...
   // Some unconditional stuff       
}

这篇关于什么是更好的方式来避免do-while(0); hack在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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