C 复合赋值C Compound Assignment

复合赋值运算符将简单赋值运算符与另一个二元运算符相结合。The compound-assignment operators combine the simple-assignment operator with another binary operator. 复合赋值运算符执行其他运算符指定的运算,然后将结果赋给左操作数。Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. 例如,一个复合赋值表达式,如For example, a compound-assignment expression such as


可以理解为can be understood as


但是,复合赋值表达式不等于扩展版本,因为复合赋值表达式只计算 expression1 一次,而扩展版本将计算 expression1 两次:在加法运算和赋值运算中。However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.

复合赋值运算符的操作数必须为整型或浮点型。The operands of a compound-assignment operator must be of integral or floating type. 每个复合赋值运算符都将执行对应的二元运算符所执行的转换并相应地限制其操作数的类型。Each compound-assignment operator performs the conversions that the corresponding binary operator performs and restricts the types of its operands accordingly. 加法赋值 (+=) 和减法赋值 (-=) 运算符还可以具有指针类型的左操作数,在此情况下,右操作数必须为整型类型。The addition-assignment (+=) and subtraction-assignment (-=) operators can also have a left operand of pointer type, in which case the right-hand operand must be of integral type. 复合赋值运算的结果具有左操作数的值和类型。The result of a compound-assignment operation has the value and type of the left operand.

#define MASK 0xff00  

n &= MASK;  

在此示例中,对 nMASK 执行了按位“与”运算,并将结果赋给了 nIn this example, a bitwise-inclusive-AND operation is performed on n and MASK, and the result is assigned to n. 使用 #define 预处理器指令定义了清单常量 MASKThe manifest constant MASK is defined with a #define preprocessor directive.

另请参阅See Also

C 赋值运算符C Assignment Operators