For Loop Boolean Problem

Hi all,

I am writing a program that deals with a maze. I need to allow for the possibility that the maze may or may not have any walls. In the for loop below, when the maze doesn't have any walls (walls.size() == 0), the for loop should never execute since I am initializing index to 0 and 0 < 0 - 1 should be false? If someone can tell me why it iterates on the < sign, but if I change it to >, then the loop body is never executed.

Thanks in advance.

1
2
3
4
for (int index = 0; index < walls.size() - 1; index += 2)
{
   //Do this
}
Last edited on
size() is a function that returns the size of something, for example a vector. The return value of size() has type "size_type". Note that this is not an int.
http://www.cplusplus.com/reference/vector/vector/size/

"size_type" is usually a size_t which in turn usually is an unsigned int. Unsigned means that it can not have a negative value, what makes sense since the size of something can not be negative.

Now you have a size_type with the value 0 and you substract 1 from that. You may have expected it to become -1, but that is not possible. Instead the variable gets the highest possible value and that is why index is always evaluated smaller than size_type(0)-1.

Instead of the "less than walls.size()-1" consider "less than walls.size()" or "less than or equal to walls.size()".

Topic archived. No new replies allowed.