Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract Signed integer from Unsigned integer [duplicate]

Tags:

c++

c

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.

like image 520
vipul Avatar asked May 30 '15 05:05

vipul


1 Answers

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.

like image 198
skrtbhtngr Avatar answered Sep 25 '22 12:09

skrtbhtngr