0

I tried the following code on https://www.onlinegdb.com/

Also tried it on Mac.

Couldn't find out why the for loop in strangeForLoop will not stop when i is equal to 0?

#include <stdio.h>
#include <stdint.h>

void strangeForLoop();
void normalForLoop();

const uint32_t COUNTDOWN = 3;
int BREAK = -2;

int main()
{
    strangeForLoop();
    printf("\n===========\n");
    normalForLoop();
    return 0;
}

void strangeForLoop() {
    for(uint32_t i = COUNTDOWN; i>=0; i--) {
        printf("strange i : %d\n", i);
        
        if (i == 0) 
            printf("--> i: %d\n", i);
        if (i == BREAK) break;
    }
}

void normalForLoop() {
    for(int i = COUNTDOWN; i>=0; i--) {
        printf("normal i : %d\n", i);
        
        if (i == 0) 
            printf("==> i: %d\n", i);
        if (i == BREAK) break;
    }
}

Any help will be greatly appreciated.

Tony
  • 111
  • 5

1 Answers1

3

i is an unsigned integer. Such a uint can represent only positive values and zero;

[0, 1, 2, 3, ... 2^number_of_bits - 1]

When an operation would decrease a uint below zero, or above its maximum, an integer overflow occurs.

In the case of this code, it wraps around to the maximum value for the integer, so the condition i >= 0 will always remain true, and the loop will never stop.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
makeVoiceBot
  • 143
  • 7
  • By standard explicit definition unsigned integers do not overflow. That is because they do not represent natural numbers, but they represent equivalence classes. Standard quotes on [this answer](https://stackoverflow.com/a/54190216/2805305) and more discussion in the comments there. – bolov Jul 18 '22 at 19:24
  • @bolov: Yes, the definition in the ISO C standard for the word "overflow" is different from the common definition. However, in my opinion, it is still correct to use the word "overflow" in this context. That just means that the common definition is being used instead of the definition used in the ISO C standard. – Andreas Wenzel Jul 18 '22 at 19:54
  • @AndreasWenzel yes, that is exactly what I did in my linked answer. However I do feel it is important to at least note the standard definition. – bolov Jul 18 '22 at 20:00