Is this a valid (ab)use of lambda expressions?

放肆的年华 提交于 2019-11-30 06:48:57

Please don't do that in a project I'm managing. That's an awkward abuse of lambdas in my opinion.

Use a goto where a goto is useful.

Perfectly valid in my opinion. Though I prefer to assign mine with names, making the code more self documenting, i.e.

int main(){

  auto DoThatOneThing = [&]{while(CheckCondition()){
    for(;;){
      if(!CheckOtherCondition())
        return;
      // do stuff...
    }
    // do stuff...
  }};

  DoThatOneThing();
  std::cout << "yep, broke out of it\n";
}

In which way is that an improvement over

void frgleTheBrgls()
{
  while(CheckCondition()) {
    for(;;) {
      if(!CheckOtherCondition())
        return;
      // do stuff...
    }
    // do stuff...
  }
}

int main()
{
  frgleTheBrgls();
  std::cout << "yep, broke out of it\n";
}

This is much well-known (functions, you know, as in BASIC), clearer (the algorithm's got a nice name explaining what it does), and does exactly the same as yours does.

Especially the function version lacks because of the missing context where the loops are called, as you'd need to pass everything you need in the loops as parameters.

I see that as an advantage. You see exactly what is needed to frgle the brgls. Explicity, when programming, often is a good thing.

One drawback with your proposed syntax: you cannot have more than 2 nested loops. The 'goto' syntax allows this:

int main()
{
    for (;;)
    {
        for (;;)
        {
            for (;;)
            {
                if (CheckCondition1()) goto BREAK_ON_COND1;
                if (CheckCondition2()) goto BREAK_ON_COND2;
                if (CheckCondition3()) break;
                // Do stuff when all conditions are false
            }
            // Do stuff when condition 3 becomes true
        }
    BREAK_ON_COND2:
        // Do stuff when condition 2 becomes true
    }
BREAK_ON_COND1: // When condition 1 becomes true
    std::cout << "yep, broke out of it\n";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!