Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and Cons of i != n vs i < n in an int for loop

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++) { ... }
}
like image 713
Bart Calixto Avatar asked Jul 04 '14 22:07

Bart Calixto


People also ask

What are the pros and cons of for loop?

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.

What are the problems while Using while loop?

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).

What is the most common problem with the use of loops in programming?

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.

Can you use int i for loop?

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.


1 Answers

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.

like image 189
mc110 Avatar answered Oct 01 '22 12:10

mc110