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.
CodePudding user response:
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.