"Ill-defined for-loop - loop executes infinitely" (MSVC C6295)

Viewed 935

I'm not quite sure why visual studio is giving me the error message "Ill-defined for-loop: 'unsigned int' values are always of range '0' to '4294967295'. Loop executes infinitely" for the following code:

for (unsigned int i = list->GetCount() - 1; i >= 0; i--)
{
    // do stuff to each item (specifically in reverse order)
}

Could someone please explain to me?

Edit: GetCount() returns an unsigned int, and I do not have control over this

2 Answers

When you subtract 0 from an unsigned type, you don't get a negative number, but a very large positive number.

That means this condition:

i >= 0

will always be true, resulting in an infinite loop.

You can fix this by doing:

for (int i = static_cast<int>(list->GetCount()) - 1; i >= 0; i--)

Note that the cast needs to be done before the subtraction by 1, otherwise you will have the same wrapping issue when GetCount returns 0.

You're making a common error here. When you declare i as an unsigned int, you are guaranteeing that it will never be negative; instead, it will "wrap around" to an extremely high number whenever it goes below 0.

What this means is that your for-loop will never terminate! Your terminating condition, i >= 0, will never be satisfied as the unsigned integer will count down 2, 1, 0, 4294967295, 4294967294... and so on forever.

To fix this, change the unsigned int type to an int type.

Related