Comparing unsigned int and int without using translation operator
Everyone I looked around has a thread about my question, but I couldn't find.
unsigned int x = 5;
int y = -3;
if(y<x)
func1();
else
func2();
func2
... But I want to func1
call.
I know that when comparing these values, I have to use the translation operator. But it is not allowed to use a translation operator or change the type of a variable.
How can I solve this problem?
source to share
Check first if the y
value is negative, then knowing that, you know that x
there will always be more as it is not specified.
If y
not negative, compare directly with x
. I don't think this will cause a problem as there is no negative sign.
See example below:
if(y<0)
{
//x>y
func1();
}
else if (y<x)
{
//lets say y=3, and x=5
func1();
}
else
{
func2();
}
source to share
Use broader math for comparison. Listing is not used, the type of variables is not changed.
The optimized compiler will not do the multiplication, only the whole expansion.
You can use * 1LL
or instead+ 0LL
int main(void) {
long long ll = 1;
unsigned int x = 5;
int y = -3;
// if (y < x)
if (ll * y < ll * x)
puts("func1();");
else
puts("func2();");
return 0;
}
Output: func1();
long long
usually wider int
: See How to define integer types that are twice as wide as `int` and` unsigned`?
source to share