size_t
is an
unsigned
datatype - it has no concept of negative numbers, so when you cast the
integer
value -1 to
size_t
what you get is a very large value because negative integers are stored with the top bit set: an eight bit value for -1 would be 11111111 in binary, and -2 would be 11111110 and so on. So when you subtract one from zero, it "overflows" to create a negative number:
Dec Binary
1 00000001
0 00000000
-1 11111111
The best way to implement a queue to to have start and end initially both zero: if they are the same value then the queue is empty, if they aren't there are elements. Add an element, and you move start, remove one, you move end (which would better be called "inIndex" and "outIndex" to better reflect what you do with them - "start" and "end" are fixed indexes for the start and end of the actual buffer space, not the values in the buffer itself)