What are the pros and cons of using one or the other iteration functions ?
function (int n) {
for (int i = 1; i != n; ++i) { ... }
}
vs
function (int n) {
for (int i = 1; i < n; i++) { ... }
}
Pros: It's straightforward. You loop through every single element for a given string or array . Cons: It's very restricting, you can't determine where to start or how long you want to go on for. Incrementing is always set to one at a time.
while loop. The potential risks and errors can be divided into two broad categories: problems with the loop control (running the loop wrong number of times), and problems with the loop actions (producing the wrong output).
One of the other most common errors in writing loops is to code a loop that never ends. This is called an infinite loop. If your program has an infinite loop, it may: display the same output over and over again.
When int i is declared outside the for loop, it can be accessed outside the for loop and inside but when you define it inside the loop, it can only be used inside the loop. Usualy, if you need it for the for loop define it inside the loop.
I think the main argument against the first version is that it is a much less common idiom.
Remembering that code is read more often than it is written, it does not make sense to use a less familiar form of for loop if there isn't a very clear advantage to doing so. All it achieves is distracting anyone working on the code in future.
So primarily for code maintenance reasons (by others as well as the original coder) I would favour the more common second format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With