Subtracting an integer from an unsigned integer

unsigned int value = 1860; int data = 1300; if( (data - value) > 0) { printf("Why it is printing this"); } 

conclusion: why does he print this

I don’t understand why the subtraction of the unsigned signed form goes through “if”, even if the value of the “data” variables is less than the “value” variable. I'm really curious how subtracting with a signature and an unsigned “small mistake”, but leads to a big one, because I used the “Delay” function instead of “printf”, and my task was delayed, creating chaos.

 unsigned int value = 1860; int data = 1300; if( (data - value) > 0) { Delay(data - value); } 

This part continues to linger, and my task never ends. This means that the value of "data-value" is negative, so it goes on endless wait. At the same time, it passes through "if", where the condition is "data-value"> 0. My doubt, if it is signed, is converted to unsigned and passes through "if", then why does it give a negative value for the Delay function.

+5
source share
1 answer

int The default data type is signed in C / C ++, i.e. supports negative numbers. When the expression contains signed and unsigned int values, signed int will be automatically converted to unsigned int , and therefore the result will be at least 0 . What you can do is:

 unsigned int value = 1860; int data = 1300; if( (signed)(data - value) > 0) { printf("Why it is printing this"); } 

It explicitly converts the result of the expression to signed so that it can be a negative number.

+8
source

All Articles