Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop?

后端 未结 21 2038
小蘑菇
小蘑菇 2020-12-23 19:48

I almost never see a for loop like this:

for (int i = 0; 5 != i; ++i)
{}

Is there a technical reason to use >

21条回答
  •  天命终不由人
    2020-12-23 20:40

    You can have something like

    for(int i = 0; i<5; ++i){
        ...
        if(...) i++;
        ...
    }
    

    If your loop variable is written by the inner code, the i!=5 might not break that loop. This is safer to check for inequality.

    Edit about readability. The inequality form is way more frequently used. Therefore, this is very fast to read as there is nothing special to understand (brain load is reduced because the task is common). So it's cool for the readers to make use of these habits.

提交回复
热议问题