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

前端 未结 13 2078
暖寄归人
暖寄归人 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:08

    The special case should be done outside the loop if it is only to be performed once.

    However, there may be an index or some other variable(s) that are just easier to keep inside the loop due to scoping. There may also be a contextual reason for keeping all the operations on the datastructure together inside the loop control structure, though I think that is a weak argument on its own.

提交回复
热议问题