Question

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-- )
{
    /* ... */
}
Was it helpful?

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.

OTHER TIPS

Performance, of course, depends on the implementation in the language used. However, in most cases and with most compilers, the generated code from both loops will pretty much be the same.

A rule of thumb would be to use while when you don't know exactly how many times you want to iterate. In your example, it doesn't make much difference. Use what's clearer to you.

And yes, declarations in the for loop are only allowed in newer versions of C (C99).

Usually, you'd use a for loop for something like that because you know before you start the loop how many times you need the loop to run. while loops are more for when you don't know how many times you're going to have to repeat, and something that the user inputs or some random int will change it

In the example above, you should use a for loop since it clearly expresses the intent of what you intend. "Do this loop num times". Also, it is much simpler for the compiler to potentially optimize for loops into vector assembly operations.

You should use a while loop when you have a clearly expressible condition like "Read lines until EOF" or some other condition that doesn't have an easily enumerable solution.

Also, I consider it poor practice to depend on the fact that 0 is false. You should clearly write the condition that exits the loop.

Every program solve in while loop that can be solved in for loop,but for loop suitable for:- 1--> If i know how many time the loop Will execute and while loop is suitable for if i don't know how many time the loop will be executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top