Is there an equivalent to the “for … else” Python loop in C++?

前端 未结 14 2054
野的像风
野的像风 2021-01-31 01:21

Python has an interesting for statement which lets you specify an else clause.

In a construct like this one:

for i in foo:
  if         


        
14条回答
  •  走了就别回头了
    2021-01-31 02:05

    I came here because I had the same question, in C though. The best thing I came out with is

    bool notTerminated = true;
    for (int i = 0; i < 50 || (notTerminated = false); i++)
        if (bar(i))
            break;
    if (! notTerminated)
        baz();
    

    Explanation: the (notTerminated = false) is an assignment that will always return the false value, it will never affect the condition and will be evaluated iif the condition if true.

提交回复
热议问题