TheGeekZn TheGeekZn - 10 days ago 6
C++ Question

while greater than negative number not working

I have a very trivial piece of code that basically needs to count down from a certain number, and use that count as an index to an array.

auto bigSize = BigArray.size() - 1;

while(bigSize > -1) {
auto thing = arr[bigSize ];
bigSize--;
}


However the code never seems to hit anything inside the loop. I've also tried with a
for
loop:

auto bigSize = BigArray.size() - 1;

for(int i = bigSize ; i >= 0 && i < bigSize ; --i) {
auto thing = arr[i];
}


I feel like I'm doing something incorrect, but I can't seem to find it.

Answer
while(bigSize > -1) {
   auto thing = arr[bigSize ];
   bigSize--;
}

This will never stop. bigSize is unsigned which means it can't contain negative values. The moment bigSize is 0 and you try to decrement it it becomes std::numeric_limits<type>::max(). (underflow, not negative) So it'll keep on looping.

Either change your condition or make bigSize explicitly an int.