For Loops
suggest changeA for statement repeats a body while its controlling expression remains true:
for (initialization; condition; iteration) {
/* body */
}
The initialization runs once. Before each iteration, the condition is evaluated; a zero result ends the loop. The iteration expression runs after each execution of the body.
For example, this loop initializes every element of an array:
#include <stddef.h>
int values[10];
for (size_t i = 0; i < 10; ++i) {
values[i] = 0;
}
Declaring i in the initialization limits its scope to the loop. This form has been standard since C99. Use size_t when an index is compared with an array size or a result of sizeof.
A for loop is not limited to a predetermined number of iterations, and any of its three expressions may be omitted. For example, for (;;) is an infinite loop unless its body transfers control elsewhere.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents