What does “for(;;)” mean?

后端 未结 5 1660
甜味超标
甜味超标 2020-12-01 09:36

In C/C++, what does the following mean?

for(;;){
    ...
}
5条回答
  •  误落风尘
    2020-12-01 09:47

    In C and C++ (and quite a few other languages as well), the for loop has three sections:

    • a pre-loop section, which executes before the loop starts;
    • an iteration condition section which, while true, will execute the body of the loop; and
    • a post-iteration section which is executed after each iteration of the loop body.

    For example:

    for (i = 1, accum = 0; i <= 10; i++)
        accum += i;
    

    will add up the numbers from 1 to 10 inclusive.

    It's roughly equivalent to the following:

    i = 1;
    accum = 0;
    while (i <= 10) {
        accum += i;
        i++;
    }
    

    However, nothing requires that the sections in a for statement actually contain anything and, if the iteration condition is missing, it's assumed to be true.

    So the for(;;) loop basically just means:

    • don't do any loop setup;
    • loop forever (breaks, returns and so forth notwithstanding); and
    • don't do any post-iteration processing.

    In other words, it's an infinite loop.

提交回复
热议问题