Assignment operators ('=' etc.)

Previous Binary operators Next

There are 11 assignment operators in C language. The '=' operator is the simple assignment operator; the other 10 ('*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=' and '|=') are known as compound assignment operators. All of them use the following syntax:

expr1 assignment-operator expr2
In the expression expr1 = expr2, expr1 must be a modifiable lvalue. The value of expr2, after conversion to the type of expr1, is stored in the object designated by expr1 (replacing expr1's previous value). The value of the assignment expression is the value of expr1 after the assignment. That's why multiple assignments like
x = y = z = 10;
a = b + 2 * (c = d - 1);
are possible. Note that the assignment expression is not itself an lvalue.

For both simple and compound assignment, the operands expr1 and expr2 must obey one of the following sets of rules:
  1. expr1 is of qualified or unqualified arithmetic type and expr2 is of arithmetic type.
  2. expr1 has a qualified or unqualified version of a structure or union type compatible with the type of expr2.
  3. expr1 and expr2 are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right.
  4. One of expr1 or expr1 is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void. The type pointed to by the left has all the qualifiers of the type pointed to by the right.
  5. expr1 is a pointer and expr2 is a null pointer constant.
The compound assignments are 'op=', where op can be any one of the ten operator symbols '*', '/', '%', '+', '-', '<<', '>>', '&', '^' or '|'. The expression
expr1 op= expr2
has the same effect as
expr1 = expr1 op expr2
except that the lvalue expr1 is evaluated only once. For example, expr1 += expr2 is the same as expr1 = expr1 + expr2.