Assignment Operators in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Assignment Operators in C.
The complete class on arithmetic operators.
There are two types of assignment operators.
- Simple Assignment Operator
- Compound Assignment Operator
The image below shows the classification of assignment operators.
Simple Assignment Operators
The simple operator ” = ” is used to store a constant value, the value of another variable or the result of expression evaluation into a variable.
For example, a = 15, b = c, or c = 20 + 40.
A critical point to understand is the assignment operator requires an Lvalue as its left operand.
An Lvalue represents an object stored in computer memory, not a constant or computation result.
An object stored in the computer memory means a variable.
The left operand of the variable should always be a variable.
It should not be an expression or a constant.
For example, 15 = b, a + b = 23, such a left operand use is not allowed.
Compound Operators
The other type of assignment operators is the compound assignment operators.
C supports a lot of compound assignment operators.
In this class, we will discuss only a few of them. [ +=, -=, *=, /=, %= ]
The compound assignment operator uses the old value of the variable to compute the new value.
For example, a += 2 is how we use the compound assignment operator.
Here a and 2 are operands, and += is a compound assignment operator.
+= means the old value of a is added with 2, and the new value is stored in the a.
a += 2 is a short form of a = a + 2 expression.
If the value of a is initialized to 12. [a = 12]
a += 2 or a = a + 2 results in 14.
The new value 14 will be stored in a.