Unless noted otherwise, these operatorsmay 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 precedence—the 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 rightwhen the precedence levels are the same.
算术表达式的优先级和结合性符合直觉,先乘除后加减,从左往右计算。
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;
Unary plus returns the operand itself. It makes no change to its operand.
CAUTION: OVERFLOW AND OTHER ARITHMETIC EXCEPTIONS
The result of eva luating some arithmetic expressions is undefined. Some expressions are undefined due to the nature of mathematics—for example, division by zero. Others are undefined due to the nature of computers—such as overflow, in which a value is computed that is too large for its type.
Consider amachine onwhich shorts are 16 bits. In that case, themaximumshort is 32767. Given only 16 bits, the following compound assignment overflows:
-
- short short_value = 32767;
- short ival = 1;
-
- 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;
- int ival2 = 21/7;
Both ival1 and ival2 are initialized with a value of 3.
注意:整数乘除法的运算顺序可能改变运算结果。比如有两个int 型变量a 和b,已知它们的最大公约数是c, 那么它们的最小公倍数是a*b/c。但是这个表达式的中间结果a*b 有溢出(即超过int 的表示范围)的可能,所以我们一般把最小公倍数公式写成a*(b/c) 或者a/c*b,以避免中间结果溢出。