C
C 语法

Assignment operators

赋值运算符

赋值和复合赋值运算符是二元运算符,它们使用右侧的值将变量修改为左侧。

OperatorOperator nameExampleDescriptionEquivalent of
=basic assignmenta = ba becomes equal to bN/A
+=addition assignmenta += ba becomes equal to the addition of a and ba = a + b
-=subtraction assignmenta -= ba becomes equal to the subtraction of b from aa = a - b
*=multiplication assignmenta *= ba becomes equal to the product of a and ba = a * b
/=division assignmenta /= ba becomes equal to the division of a by ba = a / b
%=modulo assignmenta %= ba becomes equal to the remainder of a divided by ba = a % b
&=bitwise AND assignmenta &= ba becomes equal to the bitwise AND of a and ba = a & b
|=bitwise OR assignmenta |= ba becomes equal to the bitwise OR of a and ba = a | b
^=bitwise XOR assignmenta ^= ba becomes equal to the bitwise XOR of a and ba = a ^ b
<<=bitwise left shift assignmenta <<= ba becomes equal to a left shifted by ba = a << b
=bitwise right shift assignmenta >>= ba becomes equal to a right shifted by ba = a >> b

简单的任务

简单赋值运算符表达式具有这种形式。

lhs = rhs

其中

lhs-modifiable lvalue expression of any complete object type
rhs-expression of any type implicitly convertible to lhs or compatible with lhs

赋值执行从 rhs 值到 rhs 类型的隐式转换,然后用转换后的 rhs 值替换由 lhs 指定的对象中的值。

赋值也返回与存储的值相同的值lhs(以便可能的表达式a = b = c)。赋值运算符的值类别是非左值(因此表达式(a=b)=c无效)。

rhs 和 lhs 必须满足以下条件之一:

  • lhs 和 rhs 都具有兼容的结构或联合类型,或..

注意

如果 rhs 和 lhs 在内存中重叠(例如它们是同一联合的成员),则行为不确定,除非重叠是准确的并且类型是兼容的。

虽然数组不可分配,但是包装在结构中的数组可以分配给具有相同(或兼容)结构类型的另一个对象。

更新 lhs 的副作用在值计算之后进行排序,但不是 lhs和 rhs 本身的副作用以及操作数的评估像往常一样相对于彼此不相关(所以诸如i=++i; 的表达式是未定义的)。

赋值从浮点表达式中剥离了额外的范围和精度(请参阅参考资料FLT_EVAL_METHOD)。

在 C ++中,赋值运算符是左值表达式,而不是 C.

// todo more, demo struct{array} too const char **cpp; char *p; const char c = 'A'; cpp = &p; // Error: char ** is not convertible to const char ** *cpp = &c; // OK, char* is convertible to const char* *p = 0; // OK, null pointer constant is convertible to any pointer

复合分配

复合赋值运算符表达式具有这种形式。

lhs op rhs

其中

操作-* =,/ =%=,+ = - =,<< =,>> =,&=,^ =,| =中的一个
lhs,rhs-具有算术类型的表达式(其中lhs可以是限定的或原子的),除了当op是+ =或 - =时,它们也接受与+和 - 相同限制的指针类型,

表达式 lhs @ = rhs 与 lhs =lhs @ (rhs 完全相同),只是 lhs 只被计算一次。

如果 lhs 具有原子类型,则该操作表现为具有内存顺序 memory_order_seq_cst的单个原子读取 - 修改 - 写入操作。对于整数原子类型,复合赋值@ =相当于:T1 * addr =&lhs; T2 val = rhs; T1 old = * addr; T1新; {new = old @ val} while(!atomic_compare_exchange_strong(addr,&old,new);(自C11以来)

参考

  • C11标准(ISO / IEC 9899:2011):