Why you get wrong with size_t negative loop?

Heechul Yoon·2022년 1월 14일
0

What is size_t ?

Before we go into the topic, size_t is a embedded type definition in C asunsigned int which is a result type of sizeof() function. which means, it cannot be smaller than 0 value. Once it is about to hit negative value by calculation, every bit is filped over to 1.

size_t in loop

This is my personal experience when I code a small game with C.

What I thought for size_t is a simple and ideal type to break negative loop as it cannot reach to negative value. with this naivety, I just safely thought that once i hit negative value by -- calculation, the operation is automatically stopped by program.

size_t i;
for (i = 5; i >= 0; --i) {
     printf("%d\n", i);
}

breaking down to the code, what result would you expect?

>> 5
>> 4
>> 3
>> 2
>> 1
>> 0

if you thought in this way, we are on the same ground.

the actual result is going as follow

>> 5
>> 4
>> 3
>> 2
>> 1
>> 0
>> -1
>> -2
>> -3
>> -4
...
...

size_t is represented as unsigned int type.

size_t i = 0;
i -= 1;                   [1]
printf("%d\n", i >= 0);   [2]

when the program subract 1 from 0, binary bits are filped over to the max value of unsigned int(which is 4294967295)
we call this phenomenon as underflow

this is the difference between 0 and -1 in unsigned int

  • when size_t i is 0
    0000 0000 0000 0000 0000 0000 0000 0000(2)
  • when size_t i is -1
    1111 1111 1111 1111 1111 1111 1111 1111(2)

now let me back to the negative for loop

size_t i;
for (i = 5; i >= 0; --i) {
     printf("%d\n", i);
}

i is evaluated every round by for statement and this is how it works

when i = 5, 5 >= 0 is TRUE(1)
when i = 4, 4 >= 0 is TRUE(1)
when i = 3, 3 >= 0 is TRUE(1)
when i = 2, 2 >= 0 is TRUE(1)
when i = 1, 1 >= 0 is TRUE(1)
when i = 0, 0 >= 0 is TRUE(1)
when i = -1, 4294967295 >= 0 is TRUE(1)
when i = -2, 4294967294 >= 0 is TRUE(1)
when i = -3, 4294967293 >= 0 is TRUE(1)
when i = -4, 4294967292 >= 0 is TRUE(1)
...
...

as size_t is alway evaluated as positive, program cannot get out of the loop and will be infinitely repeated.

Therefore, if you want to set break condition in negative loop, int is right type for this

profile
Quit talking, Begin doing

1개의 댓글

comment-user-thumbnail
2024년 1월 9일

This isn't your casual swipe-to-win affair; geometry dash lite's a rhythmic gauntlet of neon squares and spiky demons, a one-tap odyssey through a world where precision meets pixelated pain.

답글 달기