2

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

dbush
  • 205,898
  • 23
  • 218
  • 273
AnuragChauhan
  • 143
  • 1
  • 15

4 Answers4

2

An unsigned number will always be bigger or equal 0.

Your compiler should warn you about this error.

The reason why you are seeing negative numbers in the output is that you are printing the unsigned number using %d.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

An unsigned number will always be bigger or equal 0.

Change this

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

with

delay (uint32_t x){
    int y = 0;
    for(y=(int)x; y>= 0; y--){
         printf("Display number %d\n", y);
    }
}
Vineet1982
  • 7,730
  • 4
  • 32
  • 67
0

y is unsigned, therefore it will never be negative. You can either define it as int

int y = 0;

or modify your for to a do while

y = x;
do {
     printf("Display number %d\n", y);
} while (--y >= 0);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175