6.7 Assignment Operators

There are several assignment operators. Assignments result in the value of the target variable after the assignment. They can be used as subexpressions in larger expressions. Assignment operators do not produce lvalues.

Assignment expressions have two operands: a modifiable lvalue on the left and an expression on the right. A simple assignment consists of the equal sign (=) between two operands:

E1 = E2;

The value of expression E2 is assigned to E1. The type is the type of E1, and the result is the value of E1 after completion of the operation.

A compound assignment consists of two operands, one on either side of the equal sign (=), in combination with another binary operator. For example:

E1 += E2;

This is equivalent to the following simple assignment (except that in the compound assignment E1 is evaluated once, while in the simple assignment E1 is evaluated twice):

E1 = E1 + E2;

In the following example, the following assignments are equivalent:

a *= b + 1;

a = a * (b + 1);

In another example, the following expression adds 100 to the contents of number[1] :

number[1] += 100;

The result of this expression is the result after the addition and has the same type as number[1] .

If both assignment operands are arithmetic, the right operand is converted to the type of the left before the assignment (see Section 6.10.1).

The assignment operator (=) can be used to assign values to structures and unions. In the VAX C compatibility mode of DEC C, one structure can be assigned to another as long as the structures are defined to be the same size, in bytes. In ANSI mode, the structure values must also have the same type. With all compound assignment operators, all right operands and all left operands must be either pointers or evaluate to arithmetic values. If the operator is -= or +=, the left operand can be a pointer, and the right operand (which must be integral) is converted in the same manner as the right operand in the binary plus (+) and minus (-) operations.

Do not reverse the characters that comprise a compound assignment operator, as in the following example:

E1 =+ E2;

This is an obsolete form that is no longer supported, but it will pass through the compiler undetected. (It is interpreted as an assignment operator followed by the unary plus operator).

Previous Page | Next Page | Table of Contents | Index