for() or while() – which is BEST?
for (i=1; i<a; i++)
/* do something */
OR
i=1;
while (i<a) {
/* do something */
i++;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first is the idiomatic way; it is what most C coders will expect to see. However, I should note that most people will also expect to see
Note that the loop starts at zero. This will do something
atimes. If you’re going to write awhileloop that is equivalent to aforloop as above I strongly encourage you to write it as aforloop. Again, it is what C coders expect to see. Further, as aforloop it is easier to read as everything (initialization, loop condition, expression to be executed after each iteration) are all on one line. For thewhileloop they are spread out hindering readability.Note, however, there are circumstances in which seemingly equivalent
forandwhileloops are actually not. For example:and
appear at first glance to be equivalent but they are not. The
forloop will print0--9skipping5on the console whereas thewhileloop will print0--4on the console and then enter an infinite loop.Now, that handles the simple case that you asked about. What about the more complex cases that you didn’t ask about? Well, it really depends but a good rule of thumb is this: if you are going to repeat something a fixed pre-determined number of times, a
forloop is generally best. Otherwise, use awhileloop. This is not a hard-and-fast rule but it is a good rule-of-thumb. For example, you could writebut I think most C programmers would write this as
Or, as another example, if you’re going to read until the end of a file then you should use a
whileloop. Thusinstead of
Now, reaching into religious territory, this is why I prefer
while(1)as the right way to do an infinite loop overfor(;;).Hope that helps.