condition is evaluated only when the first argument is not sufficient to determine the value of the entire condition. Consider the following example:

int div = 0; int num = 5;

if ((div == 0) || (num / div == 1)) {

 Console.WriteLine(num); //---5---

}

Here the first expression evaluates to true, so there is no need to evaluate the second expression (because an Or expression evaluates to true as long as at least one expression evaluates to true). The second expression, if evaluated, will result in a division-by-zero error. In this case, it won't, and the number 5 is printed.

If you reverse the placement of the expressions, as in the following example, a division-by-zero error occurs:

if ((num / div == 1) || (div == 0)) {

 Console.WriteLine(num);

}

Short-circuiting also applies to the && operator — if the first expression evaluates to false, the second expression will not be evaluated because the final evaluation is already known.

Mathematical Operators

C# supports five mathematical operators, shown in the following table.

Operator Description
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulus

One interesting thing about the division operator (/) is that when you divide two integers, the fractional part is discarded:

int num1 = 6;

int num2 = 4;

double result = num1 / num2;

Console.WriteLine(result); //---1---

Here both num1 and num2 are integers and hence after the division result only contains the integer portion of the division. To divide correctly, one of the operands must be a noninteger, as the following shows:

int num1 = 6;

double num2 = 4;

double result = num1 / num2;

Console.WriteLine(result); //---1.5---

Alternatively, you can use type casting to force one of the operands to be of type double so that you can divide correctly:

int num1 = 6;

int num2 = 4;

double result = (double)num1 / num2;

Console.WriteLine(result); //---1.5---

The modulus operator (%) returns the reminder of a division:

int num1 = 6;

int num2 = 4;

int remainder = num1 % num2;

Console.WriteLine(remainder); //---2---

The % operator is commonly used for testing whether a number is odd or even, like this:

if (num1 % 2 == 0) Console.WriteLine('Even');

else Console.WriteLine('Odd');

Operator Precedence

When you use multiple operators in the same statement, you need be aware of the precedence of each operator (that is, which operator will evaluate first). The following table shows the various C# operators grouped in the order of precedence. Operators within the same group have equal precedence (operators include some keywords).

Category Operators
Primary x.y f(x) a[x] x++ x-- new typeof checked unchecked
Unary + - ! ~ ++x --x (T)x
Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату