boris dzhelali
boris dzhelali

Reputation: 197

not equals versus inequality inside for loop conditionals - in java

My colleague and I just got into a debate - that rekindled memories of university.

Specifically one of my lecturers always wrote his for loops like this :

for(int i = 0; i != max; i++){ ... }

Which seems wrong to me because it has the potential to hang your program into an infinite loop if you accidentally modify i, my colleague agrees with me.

The most common way of writing for loops, as far as I know, is :

for(int i = 0 ; i < max; i++){ ... }

So what are the pros/cons of each approach?

Upvotes: 2

Views: 576

Answers (3)

Makoto
Makoto

Reputation: 106440

If the variable is never mutated in the loop, and you increment by a value that is guaranteed to be reached from your starting value (in this case, 10), then both loops are equivalent.

If you decide to skip values during your incrementation phase, or you are not guaranteed to exactly hit the terminal condition, then the != form will result in an infinite loop.

Example:

for(int i = 0; i < 10; i += 3) { } // will stop after four iterations

for(int i = 0; i != 10; i += 3) { } // i will exceed 10, and will *not* stop

The general convention has always been to use bounded inequalities as opposed to strict inequalities when deciding a loop; that is, one loops while they are below a certain value, not while they are not at a certain value.

It is also a good thing to remain explicit and clear as to what you're iterating over, and what your end conditions are. If you specify a !=, the next person reading the code will presume that you simply don't want that number to be part of the next piece of iteration, when the intent was actually up to but not including.

Clarity is key here.

Upvotes: 4

adhg
adhg

Reputation: 10863

Tell your friend this: A smart man knows that tomato is a fruit and not a vegetable, a wise man know that you don't put tomato in a fruit salad.

Point is: yes, technically he can write this for(int i = 0; i != max; i++){ ... } but if other programer will read it - they most likely question the reason. Keep it simple and consistent.

as mentioned already: If the value changes inside the for-loop, you may end-up with infinite loop -don't do that.

Upvotes: 1

gkrls
gkrls

Reputation: 2664

1) Using the first loop, Imagine what will happen if at some point inside the loop you add someting to i so that i > max. You just got yourself a huge loop.
Of course you may really want to execute the loop as long as i != max but in that case while(i != max) is easier to read.

The only way that you are good to go with the 1st loop is if you can somehow guarantee that i will never exceed max.

2) Second loop is and easier for loop to read.

3) What if you want to loop up to and including max? you have to right i != max + 1; i++ in which case my 2nd point holds, 2nd loop is easier to read.

Upvotes: 0

Related Questions