Search code examples
cunsignedunsigned-integer

Why this loop become infinite loop in C?


Here in this code, I am using unsigned int and want to terminate my loop as soon as it reaches '0'. But this never happens it passes '0'

#include <stdio.h>
typedef unsigned int uint32_t ;

delay (uint32_t x){
    uint32_t y = 0;
    for(y=x; y>= 0; y--){
         printf("Display number %d\n", y);
    }
}

int main()
{
    uint32_t times = 10;

    printf("Hello World!\n");
    delay(10);
    return 0;
}

Output:

Hello World!
Display number 10
Display number 9
Display number 8
Display number 7
Display number 6
Display number 5
Display number 4
Display number 3
Display number 2
Display number 1
Display number 0
Display number -1
Display number -2
Display number -3
Display number -4
Display number -5
Display number -6

Link: For code from: code.hackerearth.com


Solution

  • Consider for(y=x; y>= 0; y--){ y can never be below 0 since it's an unsigned type. Once y is 0, y-- will wrap around to std::numeric_limits<uint32_t>::max(). So the for loop never terminates.

    The fact that printf is displaying negatives is a manifestation of the undefined behaviour on your using an incorrect format specifier for an unsigned type.