Search code examples
c++while-loopdeque

Why would the size of a deque be less than a small number?


I have a program in which I need to make a deque long enough to hold an item at a certain index. I use the following loop to expand the deque:

while(int1+deque1.size()<=int2){
     deque1.push_back(0);
}

When both int1 and int2 are -1 (and in many other situations; this is one I noticed while debugging), deque1 grows to a monstrous size (hundreds of thousands of items), but the loop keeps going. Why is this?


Solution

  • deque::size() returns an unsigned long int, therefore int1 and int2 MUST be positive numbers, otherwise you'll get an overflow.

    This is the code that the compiler automatically produces.

    while(static_cast<unsigned long>(int1)+deque1.size()<=static_cast<unsigned long>(int2)){
     deque1.push_back(0);
    }
    

    so if (for example) int1 is an 8 bit unsigned integer, and you give it the value -1, it will become (2^8 - 1 = 255). That's how bit encoding works in computers.

    The solution is probably the following:

    while(int1+static_cast<ptrdiff_t>(deque1.size())<=int2){
     deque1.push_back(0);
    }
    

    Cheers.