When is a do-while appropriate?

后端 未结 13 1800
Happy的楠姐
Happy的楠姐 2020-11-30 09:15

When is a do-while the better choice over other types of loops? What are some common scenarios where its better than others?

I understand the function of a do-while,

13条回答
  •  佛祖请我去吃肉
    2020-11-30 09:32

    I've used it before if I need to implement lots of conditional checks, for example processing an input form in php. Probably not the best practice, but it's more readable than many alternatives:

    do {
       if ( field1_is_invalid ) {
          $err_msg = "field1 is invalid"; break;
       }
    
       if ( field2_is_invalid ) {
          $err_msg = "field2 is invalid"; break;
       }
    
       .. check half a dozen more things ..
    
       // Only executes if all checks succeed.
       do_some_updates();
    
    } while (false)
    

    Also, I guess this isn't technically a loop. More like a way of avoiding using GOTO :)

提交回复
热议问题