Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting an overflow error within unchecked statement
    text
    copied!<pre><code>byte b; int i; unchecked { b = 255 + 255; //overflows i = 100 + int.MaxValue+100; // works } </code></pre> <p>1) Is the reason why b expression (<code>b = 255 + 255;</code>) causes an overflow error due to being affected by two conflicting rules, where first rule <strong>R1</strong> states:</p> <blockquote> <p>A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.</p> </blockquote> <p>while second rule <strong>R2</strong> states that within unchecked context overflow is allowed. </p> <p>And in the case of b expression, <strong>R1</strong> takes precedence over <strong>R2</strong>, and thus since constant expression <code>255+ 255</code> is not within the range of destination type ( which is byte ), <strong>R1</strong> causes an error, even though <strong>R2</strong> permits an overflow? </p> <p>2) </p> <p>a) Here's my reasoning as to why i expression (<code>i = 100 + int.MaxValue+100;</code>) doesn't cause an error:</p> <p>1 - When compiler starts computing i expression, it doesn't try to promote values <code>100</code> and <code>int.MaxValue</code> to type <code>long</code> before performing the addition ( thus during the computation process the two values are still of type <code>int</code> )</p> <p>2 - the addition does cause an overflow, but since this happens within unchecked context, no error is thrown</p> <p>3 - Since the two values didn't get promoted to <code>long</code>, the resulting value is also of type <code>int</code> and as such the resulting value is within the range of destination type</p> <p>b) But if instead compiler did promote <code>100</code> and <code>int.MaxValue</code>; to type <code>long</code> before performing the addition, then i expression would cause an error due to violation of rule <strong>R1</strong>?!</p> <p>thanx</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload