Tuesday, July 30, 2013

Loops

Beware of unsigned variables when writing the counting down loops.

unsigned types wrap around to give a very large positive numbers and loop never ends.

e.g.

for(size_t var (8); var >=0; --var) { //this is an infinite loop }

where as

for(int var(8); var>=0; --var) { // is a finite loop }

here var is int ( signed type) hence it will eventually become negative hence loop will terminate.

worth paying attentions to such pitfalls.