[Main]
Title=Assignment operators ('=' etc.)
Index==, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

[Top]
There are 11 assignment operators in C language.
The <CODE>'='</CODE> operator is the simple assignment operator; the other 10
(<CODE>'*='</CODE>, <CODE>'/='</CODE>, <CODE>'%='</CODE>, <CODE>'+='</CODE>, <CODE>'-='</CODE>,
<CODE>'&lt;&lt;='</CODE>, <CODE>'&gt;&gt;='</CODE>, <CODE>'&amp;='</CODE>,
<CODE>'^='</CODE> and <CODE>'|='</CODE>)
are known as compound assignment operators.
All of them use the following syntax:
<PRE><I>expr1</I> <I>assignment-operator</I> <I>expr2</I>
</PRE>
In the expression <I>expr1</I>&nbsp;=&nbsp;<I>expr2</I>,
<I>expr1</I> must be a modifiable <A HREF="$$LINK(lvalue)">lvalue</A>.
The value of <I>expr2</I>, after conversion to the type of <I>expr1</I>, is
stored in the object designated by <I>expr1</I> (replacing
<I>expr1</I>'s previous value). The value of the assignment expression is the value of
<I>expr1</I> after the assignment. That's why multiple assignments like
<PRE>x = y = z = 10;
a = b + 2 * (c = d - 1);
</PRE>
are possible. Note that the assignment expression is not itself an lvalue.
<BR><BR>
For both simple and compound assignment, the operands <I>expr1</I> and <I>expr2</I> must obey
one of the following sets of rules:
<OL>
<LI>
<I>expr1</I> is of qualified or unqualified arithmetic type and
<I>expr2</I> is of arithmetic type.
</LI>
<LI>
<I>expr1</I> has a qualified or unqualified version
of a structure or union type compatible with the type of <I>expr2</I>.
</LI>
<LI>
<I>expr1</I> and <I>expr2</I>
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.
</LI>
<LI>
One of <I>expr1</I> or <I>expr1</I> 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.
</LI>
<LI>
<I>expr1</I> is a pointer and <I>expr2</I> is a null pointer constant.
</LI>
</OL>
The compound assignments are <CODE>'<I>op</I>='</CODE>, where <I>op</I> can be any one of
the ten operator symbols <CODE>'*'</CODE>, <CODE>'/'</CODE>, <CODE>'%'</CODE>, <CODE>'+'</CODE>,
<CODE>'-'</CODE>, <CODE>'&lt;&lt;'</CODE>, <CODE>'&gt;&gt;'</CODE>, <CODE>'&amp;'</CODE>,
<CODE>'^'</CODE> or <CODE>'|'</CODE>. The expression
<PRE><I>expr1</I> <I>op</I>= <I>expr2</I></PRE>
has the same effect as
<PRE><I>expr1</I> = <I>expr1</I> <I>op</I> <I>expr2</I></PRE>
except that the lvalue <I>expr1</I> is evaluated only once. For example, <I>expr1</I>&nbsp;+=&nbsp;<I>expr2</I> is
the same as <I>expr1</I>&nbsp;=&nbsp;<I>expr1</I>&nbsp;+&nbsp;<I>expr2</I>.
