X hits on this document





150 / 396

Chapter ‎18   Unsafe code

The checked and unchecked operators only affect the overflow checking context for those operations that are textually contained within the “(” and “)” tokens. The operators have no effect on function members that are invoked as a result of evaluating the contained expression. In the example

class Test { static int Multiply(int x, int y) { return x * y; }

static int F() { return checked(Multiply(1000000, 1000000)); } }

the use of checked in F does not affect the evaluation of x * y in Multiply, so x * y is evaluated in the default overflow checking context.

The unchecked operator is convenient when writing constants of the signed integral types in hexadecimal notation. For example:

class Test { public const int AllBits = unchecked((int)0xFFFFFFFF);

public const int HighBit = unchecked((int)0x80000000); }

Both of the hexadecimal constants above are of type uint. Because the constants are outside the int range, without the unchecked operator, the casts to int would produce compile-time errors.

The checked and unchecked operators and statements allow programmers to control certain aspects of some numeric calculations. However, the behavior of some numeric operators depends on their operands’ data types. For example, multiplying two decimals always results in an exception on overflow even within an explicitly unchecked construct. Similarly, multiplying two floats never results in an exception on overflow even within an explicitly checked construct. In addition, other operators are never affected by the mode of checking, whether default or explicit.

7.6 Unary operators

The +, -, !, ~, ++, --, and cast operators are called the unary operators.

unary-expression: primary-expression +   unary-expression -   unary-expression !   unary-expression ~   unary-expression pre-increment-expression pre-decrement-expression cast-expression

7.6.1 Unary plus operator

For an operation of the form +x, unary operator overload resolution (§‎7.2.3) is applied to select a specific operator implementation. The operand is converted to the parameter type of the selected operator, and the type of the result is the return type of the operator. The predefined unary plus operators are:

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

Document info
Document views1329
Page views1329
Page last viewedSat Jan 21 17:55:47 UTC 2017