Loops in C - for() or while() - which is BEST?

前端 未结 4 945
梦谈多话
梦谈多话 2021-01-12 19:28

for() or while() - which is BEST?

for (i=1; i

OR

i=1;
while (i

        
4条回答
  •  感动是毒
    2021-01-12 20:14

    Vote up for Dan McG - if the loop has a fixed count, etc., use for - it's more idiomatic. Classic cases of each:

    for (i = 0; i < THRESHOLD; ++i) {
      something;
    }
    

    Vs.

    while (foo->next) {
      foo = foo -> next; 
    }
    

    Also: if you find yourself leaving out conditions in your for, consider what it would be like if you reworte it as a while.

    At the end of the day: go back and read each version of the loop. Which one stands out more in your mind as "clear" in intent?

提交回复
热议问题