Assignment Operator in C

We have already used the assignment operator ( = ) several times before. Let’s discuss it here in detail.

The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows:

The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:

The precedence of the assignment operator is lower than all the operators we have discussed so far and it associates from right to left.

We can also assign the same value to multiple variables at once.

here x, y and z are initialized to 100.

Since the associativity of the assignment operator ( = ) is from right to left. The above expression is equivalent to the following:

Note that expressions like:

are called assignment expression. If we put a semicolon(;) at the end of the expression like this:

then the assignment expression becomes assignment statement.

Compound Assignment Operator

Assignment operations that use the old value of a variable to compute its new value are called Compound Assignment.

Consider the following two statements:

Here the second statement adds 5 to the existing value of x. This value is then assigned back to x. Now, the new value of x is 105.

To handle such operations more succinctly, C provides a special operator called Compound Assignment operator.

The general format of compound assignment operator is as follows:

where op can be any of the arithmetic operators (+, -, *, /, %). The above statement is functionally equivalent to the following:

Note: In addition to arithmetic operators, op can also be >> (right shift), << (left shift), | (Bitwise OR), & (Bitwise AND), ^ (Bitwise XOR) . We haven’t discussed these operators yet.

After evaluating the expression, the op operator is then applied to the result of the expression and the current value of the variable (on the RHS). The result of this operation is then assigned back to the variable (on the LHS).

Let’s take some examples:

The statement:

is equivalent to x = x + 5; or x = x + (5);.

Similarly, the statement:

is equivalent to x = x * 2; or x = x * (2);.

Since, expression on the right side of op operator is evaluated first, the statement:

is equivalent to x = x * (y + 1).

The precedence of compound assignment operators are same and they associate from right to left (see the precedence table).

The following table lists some Compound assignment operators:

Operator Description
+= x += 5 equivalent to x = x + 5
-= y -= 5 equivalent to y = y - 5
/= z /= 3 equivalent to z = z / 5
%= m %= 10 equivalent to m = m % 10

The following program demonstrates Compound assignment operators in action:

Expected Output:

1 thought on “Assignment Operator in C

Leave a Comment

%d bloggers like this: