在c ++中使用goto的合法理由

时间:2011-06-25 06:17:41

标签: c++ syntax goto

  

可能重复:
  GOTO considered harmless
  GOTO still considered harmful?

有没有合理的理由在c ++程序中使用goto?我认识的每个人都说goto的定义是你编写错误的东西,我同意,因为我找不到任何使用goto的理由

3 个答案:

答案 0 :(得分:11)

goto是一种优雅+高效的方法来处理这个问题:

for (...) {
   for (...) {
      for (...) {
          /* detect condition that requires breaking all three loops */

      }
   }
}
out:

另一个例子。假设你有一个巨大的功能 - 2K线。不要惊讶,很多网络代码都有这个。在函数中,您可以在不同时间检测需要相同错误处理的条件:goto对此有所了解。

编辑以下链接部分原始文章反驳了Dijkstra的文章。

"GOTO statement considered harmful" considered harmful

答案 1 :(得分:4)

当您需要突破深层嵌套循环时。假设您正在三维矩阵中搜索值:

for( size_t i = 0; i != d0; ++i )
for( size_t j = 0; j != d1; ++j )
for( size_t k = 0; k != d2; ++k )
  if( m[i][j][k] == key )
  {
    // break out
  }

当然你总是可以定义一个函数和return,但你可能有一次性的用例,其中编写一个函数(从而将代码移出上下文,携带所有变量,等等,以避免使用goto

是不值得的

答案 2 :(得分:2)

您可以使用goto进行清理,例如:

void doSomething()
{
    if (someCondition)
        goto cleanUPA;
    if (otherCondition)
        goto cleanUPB;
    if (oneMoreCondition)
        goto cleanUPAll;

    //All good then just
    return;

cleanupUPB:
    //respective cleanups
cleanupUPA:
    //respective cleanups
cleanUPALL:
    //respective cleanups
}

可能,可以通过在C ++中使用RAII以更好的方式实现,但是来自C背景,这通常是使用goto的地方,所以如果由于任何原因你不能使用RAII(我认为很难找到这种情况 - 可能你根本就没有使用任何智能指针等等)然后它可能是一个合法的案例。