unsigned int value = 1860;
int data = 1300;
if( (data - value) > 0)
{
printf("Why it is printing this");
}
output : Why it is printing this
I am not understanding why subtraction of signed form unsigned pass through the "if" even though value of variable "data" is less than variable "value". I am really curious how signed and unsigned subtraction 'a small mistake' but leads to a big one because I was using "Delay" function instead of "printf" and my task was getting delayed which was creating chaos.
unsigned int value = 1860;
int data = 1300;
if( (data - value) > 0)
{
Delay(data - value);
}
This part is keep on delaying and my task never ends.That means value of "data - value" is negative that's why it goes on infinite waiting. Simultaneously it is passing through the "if" where , the condition is "data-value" > 0 . My Doubt if signed gets converted in unsigned and passes through "if" , then why it is giving negative value to "Delay" function.
int
data type is by default signed
in C/C++ i.e. supports negative numbers. When an expression contains both signed
and unsigned
int
values, the signed int
will be automatically converted to unsigned int
and so the result will not be less than 0
.
What you may want to do is this:
unsigned int value = 1860;
int data = 1300;
if( (signed)(data - value) > 0)
{
printf("It should print this!");
}
It explicitly converts the result of expression to a signed
value so that it may be a negative number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With