Home > OS >  integer promotion in c# (the range of an sbyte as an example)
integer promotion in c# (the range of an sbyte as an example)

Time:04-03

so I am studying about Integer Promotion and I know that type promotions only apply to the values operated upon when an expression is evaluated. I have this example where I take an sbyte that is equal to 127 and increment it by 1 and then I output it on the Console and I get a -128. Does this mean that the sbyte turns into an int during the process of incrementing and then it somehow transforms into a -128. I would like to know how exactly this happens.

        sbyte efhv = 127;
        efhv  ;
        Console.WriteLine(efhv);

CodePudding user response:

As @Sweeper pointed out in the comments, integer promotion does not apply to the operator: modifies the value in-place, which means that the modified value must be within the range of the specified data type. Integer promotion would not make any sense here.

As @beautifulcoder explained in their answer, the effect you see is simply a two's complement number overflowing, since C# executes arithmetic operations in an unchecked context by default.

According to the C# language specification integer promotion does occur for the unary and the binary operators, as can be seen in the following code example:

sbyte efhv = 127;
sbyte one = 1;

Console.WriteLine((efhv).GetType().Name);       // prints SByte
Console.WriteLine((efhv  ).GetType().Name);     // prints SByte
Console.WriteLine(( efhv).GetType().Name);      // prints Int32
Console.WriteLine((efhv   one).GetType().Name); // prints Int32

(fiddle)

CodePudding user response:

It is because this is a signed 8-bit integer. When the value exceeds the max it overflows into the negative numbers. It is not promotion but overflow behavior you are seeing.

To verify:

sbyte efhv = 127;
efhv  ;
Console.WriteLine(efhv);

Console.WriteLine(sbyte.MaxValue);
Console.WriteLine(sbyte.MinValue);
  •  Tags:  
  • c#
  • Related