Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int promotion to unsigned int in C and C#

Tags:

c

c#

int

Have a look at this C code:

int main()
{
    unsigned int y = 10;
    int x = -2;
    if (x > y)
        printf("x is greater");
    else
        printf("y is greater");
    return 0;
}
/*Output: x is greater.*/ 

I understand why the output is x is greater, because when the computer compares both of them, x is promoted to an unsigned integer type. When x is promoted to unsigned integer, -2 becomes 65534 which is definitely greater than 10.

But why in C#, does the equivalent code give the opposite result?

public static void Main(String[] args)
{
    uint y = 10;
    int x = -2;
    if (x > y)
    {
        Console.WriteLine("x is greater");
    }
    else
    {
        Console.WriteLine("y is greater");
    }
}
//Output: y is greater. 
like image 278
David Klempfner Avatar asked Aug 06 '13 23:08

David Klempfner


People also ask

What is integer promotion in C?

CProgrammingServer Side Programming. There are some data types which take less number of bytes than integer datatype such as char, short etc. If any operations are performed on them, they automatically get promoted to int. This is known as integer promotions.

How do I convert an int to unsigned?

You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

What is operator promotion in C?

Type Promotion in C. Introduction. Type promotion in C is a method to convert any variable from one datatype to another. C allows variables of different datatypes to be present in a single expression. There are different types of type conversions available in C.

What is implicit type promotion?

Whenever a small integer type is used in an expression, it is implicitly converted to int which is always signed. This is known as the integer promotions or the integer promotion rule.


1 Answers

In C#, both uint and int get promoted to a long before the comparison.

This is documented in 4.1.5 Integral types of the C# language spec:

For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of both operands. The operation is then performed using the precision of type T, and the type of the result is T (or bool for the relational operators). It is not permitted for one operand to be of type long and the other to be of type ulong with the binary operators.

Since long is the first type that can fully represent all int and uint values, the variables are both converted to long, then compared.

like image 92
Reed Copsey Avatar answered Sep 21 '22 19:09

Reed Copsey