Search code examples
cfor-loopwhile-loopcycle

While vs. for: what is the best?


If I can do a cycle with for and while both, which should I choose?

[for]

int num = 10;
int i;

for (i=0; i<num; i++)
{
    /* ... */
}

[while]

int num = 10;
int i = num;

while ( i-- )
{
    /* ... */
}

Solution

  • The choice between for and while is just matter of clarity:

    K&R . Chapter 1. The For statment:

    The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.