Assignment Operator in C

We have already used assignment operator while assigning a value to the variable. Let’s discuss it here again in detail.

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

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

here x, y and z are initialized to 100.

Note: Expression 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 old value of a variable to compute its new value are called Compound Assignment. For example, the following statement adds 5 to the existing value of x.

Here first, the existing value of x is added to 5, this value is then assigned back to x. Now x is 105.

It turns out that C provides some special operators for this kind of operations.

is same as x = x + 5 but it is more concise and easy to type.

+= is known as Compound assignment operator.

Similarly we have other 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.

Expected Output:

Leave a Comment