Is while (true) with break bad programming practice?

后端 未结 22 2282
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:38

I often use this code pattern:

while(true) {

    //do something

    if() {
        break;
    }

}   

Another progr

22条回答
  •  悲&欢浪女
    2020-11-27 04:57

    The problem is that not every algorithm sticks to the "while(cond){action}" model.

    The general loop model is like this :

    loop_prepare
     loop:
      action_A
      if(cond) exit_loop
      action_B
      goto loop
    after_loop_code
    

    When there is no action_A you can replace it by :

    loop_prepare
      while(cond)
      action_B
    after_loop_code
    

    When there is no action_B you can replace it by :

    loop_prepare
      do action_A
      while(cond)
    after_loop_code
    

    In the general case, action_A will be executed n times and action_B will be executed (n-1) times.

    A real life example is : print all the elements of a table separated by commas. We want all the n elements with (n-1) commas.

    You always can do some tricks to stick to the while-loop model, but this will always repeat code or check twice the same condition (for every loops) or add a new variable. So you will always be less efficient and less readable than the while-true-break loop model.

    Example of (bad) "trick" : add variable and condition

    loop_prepare
    b=true // one more local variable : more complex code
     while(b): // one more condition on every loop : less efficient
      action_A
      if(cond) b=false // the real condition is here
      else action_B
    after_loop_code
    

    Example of (bad) "trick" : repeat the code. The repeated code must not be forgotten while modifying one of the two sections.

    loop_prepare
    action_A
     while(cond):
      action_B
      action_A
    after_loop_code
    

    Note : in the last example, the programmer can obfuscate (willingly or not) the code by mixing the "loop_prepare" with the first "action_A", and action_B with the second action_A. So he can have the feeling he is not doing this.

提交回复
热议问题