How to jump out of a C++ code block?

前端 未结 7 801
无人及你
无人及你 2021-01-04 19:22

This is what I would like to do:

{
    ...
    if(condition)
        break;
    ...
}

This works for a loop. I would like something similar

相关标签:
7条回答
  • 2021-01-04 19:54

    In C++11 the best way to achieve this is use a anonymous lambda function and replacing break with return

    [&](){
        ...
        if(condition)
            return;
        ...
     }();
    

    Note that [&] captures all variables by reference, if you don't use any just replace it with []

    0 讨论(0)
  • 2021-01-04 19:56

    I'm afraid I'm unleashing the wrath of a coding god against me right now, but this nice nasty macro could help people do this easier than before (based on @jleahy's answer):

    //example use:
    // { __breakable__
    //    ...
    //    if (condition)
    //        break;
    //    ...
    //    if (condition2)
    //        break;
    //    ...
    // }
    //WARNING: use only with a standalone block. To make if, try or catch block
    //         breakable use double braces
    //         if (cond) {{ __breakable__ ... }}
    //         try {{ __breakable__ ... }} catch (...) {{ __breakable__ ... }}
    #define __breakable__ }switch(0){default:
    
    0 讨论(0)
  • 2021-01-04 20:03

    "I would like something similar for a simple block of code."

    Use return after a condition is met, and return control back to the caller.

    void MyWorkerClass::doWork(Item & workItem) {
        // ...
        if(noMoreWorkToDo)
            return;
        // ...
    }
    
    0 讨论(0)
  • 2021-01-04 20:05

    Here just some additional possibilities:

    for(..)
    {
        continue;//next loop iteration
    }
    
    void mymethod()
    {
        ...
        return;
        ...
    }
    

    Probably you should create sub-methods for the problematic block of code were you wanted to use goto and leave the block of code by the usage of return.

    0 讨论(0)
  • 2021-01-04 20:12

    This one:

    {
        // ...
    
        if (!condition)
        {
            // ...
        }
    }
    

    This will avoid goto to jump out of a block of code.

    0 讨论(0)
  • 2021-01-04 20:12

    Here's one way:

    switch(0) {
    default:
        /* code */
        if (cond) break;
        /* code */
    }
    

    (please never do this)

    0 讨论(0)
提交回复
热议问题