Assignment Operators
Overview
In computer programming, assignment operators are used to assign values to variables. The operators are essential in manipulating data and updating variables with new values. A value can be stored in a variable using the assignment operator.
Simple Assignment Operator
The simple assignment operator ( =) assigns the value on the right side of the operator to the variable on the left side. The operand on the left-hand side(LHS) should be a variable. The operand on the right-hand side(RHS) can be any variable, constant, or expression. The value of the right-hand operand is assigned to the left-hand operand.
Examples
Some examples of assignment expressions:
x = 8; /* 9 is assigned to the variable x */
In the above programming statement, the value 9 is assigned to the variable x.
y=x;
In the above programming statement, the value of the variable x is assigned to the variable y.
expr = x+y+3; /* The value of expression x+y+3
is assigned to the variable expr */
In the above programming statement, the value of the expression x+y+3 is assigned to the variable expr.
We can also have multiple assignment operators in a single statement. For example, the three variables x,y, and z will be assigned the value 6.
x=y=z=6;
Compound Assignment Operators
When the variable on the lefthand side of the assignment operator also occurs on the right-hand side, we can avoid writing the variable twice by using compound assignment operators.
x+=9;
For example, x=x+9 can also be written as x+=9. The += is a compound assignment operator called as the Add and Assign Operator.
x-=7; /* is equivalent to x=x-7 */
x*=7; /* is equivalent to x=x*7 */
x/=7; /* is equivalent to x=x/5 */