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
}
"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()".