Assignment Operators
Unlike many other programming languages, C treats value assignment as operation (represented by an operator) rather than instruction.
Simple Assignment Operator
For a common value assignment, a simple assignment operator (=
) is used:
expression1 = expression2
The expression1
is an object (memory location) to which the value of expression2
is assigned. Operand expression1
has to be lvalue and expression2
can be any expression. The assignment expression itself is not lvalue.
If expression1
and expression2
are of different types, the result of the expression2
will be converted to the type of expression1
, if necessary. Refer to Type Conversions for more information.
Compound Assignment Operators
C allows more comlex assignments by means of compound assignment operators. The syntax of compound assignment operators is:
expression1 op= expression2
where op
can be one of binary operators +
, -
, *
, /
, %
, &
, |
, ^
, <<
, or >>
.
Thus, we have 10 different compound assignment operators: +=
, -=
, *=
, /=
, %=
, &=
, |=
, ^=
, <<=
and >>=
. All of them associate from right to left. Spaces separating compound operators (e.g. + =
) will generate error.
Compound assignment has the same effect as
expression1 = expression1 op expression2
except the lvalue expression1
is evaluated only once. For example, expression1
+= expression2
is the same as expression1
= expression1
+ expression2
.
Assignment Rules
For both simple and compound assignment, the operands expression1
and expression2
must obey one of the following rules:
expression1
is of qualified or unqualified arithmetic type andexpression2
is of arithmetic type.expression1
has a qualified or unqualified version of structure or union type compatible with the type ofexpression2
.expression1
andexpression2
are pointers to qualified or unqualified versions of compatible types and the type pointed to by left has all qualifiers of the type pointed to by right.- Either
expression1
orexpression2
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 left has all qualifiers of the type pointed to by right. expression1
is a pointer andexpression2
is a null pointer constant.
What do you think about this topic ? Send us feedback!