Does the last element in a loop deserve a separate treatment?

前端 未结 13 2103
暖寄归人
暖寄归人 2020-12-15 18:55

When reviewing, I sometimes encounter this kind of loop:

i = begin
while ( i != end ) {    
   // ... do stuff
   if ( i == end-1 (the one-but-last element)          


        
13条回答
  •  情深已故
    2020-12-15 19:10

    @xtofl,

    I agree with your concern.

    Million times I encountered similar problem.

    Either developer adds special handling for first or for last element.

    In most cases it is worth to just loop from startIdx + 1 or to endIdx - 1 element or even split one long loop into multiple shorter loops.

    In a very rare cases it's not possible to split loop.

    In my opinion uncommon things should be handled outside of the loop whenever possible.

提交回复
热议问题