do {…} while(false)

前端 未结 25 2298
小鲜肉
小鲜肉 2020-11-28 03:29

I was looking at some code by an individual and noticed he seems to have a pattern in his functions:

 function()
{
 

        
相关标签:
25条回答
  • 2020-11-28 04:10

    It's a contrived way to emulate a GOTO as these two are practically identical:

    // NOTE: This is discouraged!
    do {
        if (someCondition) break;
        // some code be here
    } while (false);
    // more code be here
    

    and:

    // NOTE: This is discouraged, too!
    if (someCondition) goto marker;
    // some code be here
    marker:
    // more code be here
    

    On the other hand, both of these should really be done with ifs:

    if (!someCondition) {
        // some code be here
    }
    // more code be here
    

    Although the nesting can get a bit ugly if you just turn a long string of forward-GOTOs into nested ifs. The real answer is proper refactoring, though, not imitating archaic language constructs.

    If you were desperately trying to transliterate an algorithm with GOTOs in it, you could probably do it with this idiom. It's certainly non-standard and a good indicator that you're not adhering closely to the expected idioms of the language, though.

    I'm not aware of any C-like language where do/while is an idiomatic solution for anything, actually.

    You could probably refactor the whole mess into something more sensible to make it more idiomatic and much more readable.

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