5.1. 算术操作符

Unless noted otherwise, these operators may be applied to any of the arithmetic types (Section 2.1, p. 34), or any type that can be converted to an arithmetic type.

The table groups the operators by their precedencethe unary operators have the highest precedence, then the multiplication and division operators, and then the binary addition and subtraction operators. Operators of higher precedence group more tightly than do operators with lower precedence. These operators are all left associative, meaning that they group left to right when the precedence levels are the same.

表 5.1. 算术操作符

Operator

Function

Use

+

unary plus（一元正号）

+ expr

-

unary minus（一元负号）

- expr

*

multiplication（乘法）

expr * expr

/

division（除法）

expr / expr

%

remainder（求余）

expr % expr

+

addition（加法）

expr + expr

-

subtraction（减法）

expr - expr

Applying precedence and associativity to the previous expression:

```     5 + 10 * 20/2;
```

we can see that the operands to the multiplication operator (*) are 10 and 20. The result of that expression and 2 are the operands to the division operator (/). The result of that division and 5 are the operands to the addition operator (+).

The unary minus operator has the obvious meaning. It negates its operand:

```     int i = 1024;
int k = -i; //  negates the value of its operand
```

Unary plus returns the operand itself. It makes no change to its operand.

警告：溢出和其他算术异常

The result of evaluating some arithmetic expressions is undefined. Some expressions are undefined due to the nature of mathematicsfor example, division by zero. Others are undefined due to the nature of computerssuch as overflow, in which a value is computed that is too large for its type.

Consider a machine on which shorts are 16 bits. In that case, the maximum short is 32767. Given only 16 bits, the following compound assignment overflows:

```     // max value if shorts are 8 bits
short short_value = 32767;
short ival = 1;
// this calculation overflows
short_value += ival;
cout << "short_value: " << short_value << endl;
```

Representing a signed value of 32768 requires 17 bits, but only 16 are available. On many systems, there is no compile-time or run-time warning when an overflow might occur. The actual value put into short_value varies across different machines. On our system the program completes and writes

```     short_value: -32768
```

The value "wrapped around:" The sign bit, which had been 0, was set to 1, resulting in a negative value. Because the arithmetic types have limited size, it is always possible for some calculations to overflow. Adhering to the recommendations from the "Advice" box on page 38 can help avoid such problems.

The binary + and - operators may also be applied to pointer values. The use of these operators with pointers was described in Section 4.2.4 (p. 123).

The arithmetic operators, +, -, *, and / have their obvious meanings: addition, subtraction, multiplication, and division. Division between integers results in an integer. If the quotient contains a fractional part, it is truncated:

```     int ival1 = 21/6;  //  integral result obtained by truncating the remainder
int ival2 = 21/7;  //  no remainder, result is an integral value
```

Both ival1 and ival2 are initialized with a value of 3.

ival1ival2 均被初始化为 3

The % operator is known as the "remainder" or the "modulus" operator. It computes the remainder of dividing the left-hand operand by the right-hand operand. This operator can be applied only to operands of the integral types: bool, char, short, int, long, and their associated unsigned types:

```     int ival = 42;
double dval = 3.14;
ival % 12;   //  ok: returns 6
ival % dval; //  error: floating point operand
```

For both division (/) and modulus(%), when both operands are positive, the result is positive (or zero). If both operands are negative, the result of division is positive (or zero) and the result of modulus is negative (or zero). If only one operand is negative, then the value of the result is machine-dependent for both operators. The sign is also machine-dependent for modulus; the sign is negative (or zero) for division:

```     21 % 6;   //  ok: result is 3
21 % 7;   //  ok: result is 0
-21 % -8; //  ok: result is -5
21 % -5;  //  machine-dependent: result is 1 or -4
21 / 6;   //  ok: result is 3
21 / 7;   //  ok: result is 3
-21 / -8; //  ok: result is 2
21 / -5;  //  machine-dependent: result -4 or -5
```

When only one operand is negative, the sign and value of the result for the modulus operator can follow either the sign of the numerator or of the denominator. On a machine where modulus follows the sign of the numerator then the value of division truncates toward zero. If modulus matches the sign of the denominator, then the result of division truncates toward minus infinity.

Exercises Section 5.1

 Exercise 5.1: Parenthesize the following expression to indicate how it is evaluated. Test your answer by compiling the expression and printing its result. 在下列表达式中，加入适当的圆括号以标明其计算顺序。编译该表达式并输出其值，从而检查你的回答是否正确。 ``` 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 ``` Exercise 5.2: Determine the result of the following expressions and indicate which results, if any, are machine-dependent. 计算下列表达式的值，并指出哪些结果值依赖于机器？ ``` -30 * 3 + 21 / 5 -30 + 3 * 21 / 5 30 / 3 * 21 % 5 -30 / 3 * 21 % 4 ``` Exercise 5.3: Write an expression to determine whether an int value is even or odd. 编写一个表达式判断一个 int 型数值是偶数还是奇数。 Exercise 5.4: Define the term overflow. Show three expressions that will overflow. 定义术语“溢出”的含义，并给出导致溢出的三个表达式。