Useful alternative control structures?

后端 未结 28 926
礼貌的吻别
礼貌的吻别 2021-01-30 02:20

Sometimes when I am programming, I find that some particular control structure would be very useful to me, but is not directly available in my programming language. I think my

28条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 03:04

    Something that replaces

    bool found = false;
    for (int i = 0; i < N; i++) {
      if (hasProperty(A[i])) {
        found = true;
        DoSomething(A[i]);
        break;
      }
    }
    if (!found) {
      ...
    }
    

    like

    for (int i = 0; i < N; i++) {
      if (hasProperty(A[i])) {
        DoSomething(A[i]);
        break;
      }
    } ifnotinterrupted {
      ...
    }
    

    I always feel that there must be a better way than introducing a flag just to execute something after the last (regular) execution of the loop body. One could check !(i < N), but i is out of scope after the loop.

提交回复
热议问题