X hits on this document

940 views

0 shares

0 downloads

0 comments

149 / 396

C# LANGUAGE SPECIFICATION

In an unchecked context, the result is truncated by discarding any high-order bits that do not fit in the destination type.

For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.

For constant expressions (expressions that can be fully evaluated at compile-time), the default overflow checking context is always checked. Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression always cause compile-time errors.

In the example

class Test { static readonly int x = 1000000; static readonly int y = 1000000;

static int F() { return checked(x * y);// Throws OverflowException }

static int G() { return unchecked(x * y);// Returns -727379968 }

static int H() { return x * y;// Depends on default } }

no compile-time errors are reported since neither of the expressions can be evaluated at compile-time. At run-time, the F method throws a System.OverflowException, and the G method returns –727379968 (the lower 32 bits of the out-of-range result). The behavior of the H method depends on the default overflow checking context for the compilation, but it is either the same as F or the same as G.

In the example

class Test { const int x = 1000000; const int y = 1000000;

static int F() { return checked(x * y);// Compile error, overflow }

static int G() { return unchecked(x * y);// Returns -727379968 }

static int H() { return x * y;// Compile error, overflow } }

the overflows that occur when evaluating the constant expressions in F and H cause compile-time errors to be reported because the expressions are evaluated in a checked context. An overflow also occurs when evaluating the constant expression in G, but since the evaluation takes place in an unchecked context, the overflow is not reported.

136Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views940
Page views940
Page last viewedThu Dec 08 00:36:44 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments