int n = 5; for(int i = 0;i!=n;i++)//condition != { //executing 5times } int n = 5; for(int i = 0;i<n;i++)//condition < { //executing 5times }
Which one is preferred?
This was example from ‘Accelerated C++ : practical programming by example / Andrew Koenig, Barbara E. Moo.’ Just wanted to know why the Author prefers the first one
The second. For two reasons
The less than (or sometimes <=) is the usual way that most coder write these, and it’s better to stick to convention if possible – the != will probably make most coders look twice to check if there’s something odd in the loop whereas the < will be instantly understood.
The != depends on an exact condition. If the interior of the loop is modified during maintenance and i accidentally incremented inside the loop then you would end up with an infinite loop. Generally it’s always better to make your termination condition as wide as possible – it’s simply more robust.
2 is of course the reason why 1.