In programming, assignment operators are used to assign values to variables. Basic and compound assignment operators are two types of these operators.
Basic Assignment Operator (=
)
The basic assignment operator is represented by the single equal sign (=
). It assigns the value of the expression on its right-hand side to the variable on the left-hand side. For example:
Here, the value 5
is assigned to the variable a
. After this statement, the value of a
will be 5
.
Compound Assignment Operators
Compound assignment operators are shorthand versions of their corresponding basic assignment operator combined with an arithmetic or bitwise operation. These operators modify the value of a variable based on its current value and the operation on the right-hand side.
Here are the most common compound assignment operators:
-
+=
(Addition assignment): Adds the right-hand value to the left-hand value and assigns the result to the left-hand variable. -
-=
(Subtraction assignment): Subtracts the right-hand value from the left-hand value and assigns the result to the left-hand variable. -
*=
(Multiplication assignment): Multiplies the left-hand value by the right-hand value and assigns the result to the left-hand variable. -
/=
(Division assignment): Divides the left-hand value by the right-hand value and assigns the result to the left-hand variable. -
%=
(Modulus assignment): Takes the modulus of the left-hand value with the right-hand value and assigns the result to the left-hand variable. -
&=
(Bitwise AND assignment): Performs a bitwise AND between the left-hand value and the right-hand value, then assigns the result to the left-hand variable. -
|=
(Bitwise OR assignment): Performs a bitwise OR between the left-hand value and the right-hand value, then assigns the result to the left-hand variable. -
^=
(Bitwise XOR assignment): Performs a bitwise XOR between the left-hand value and the right-hand value, then assigns the result to the left-hand variable. -
<<=
(Bitwise left shift assignment): Performs a left shift operation on the left-hand value by the number of positions specified by the right-hand value, then assigns the result to the left-hand variable. -
>>=
(Bitwise right shift assignment): Performs a right shift operation on the left-hand value by the number of positions specified by the right-hand value, then assigns the result to the left-hand variable.
These compound operators provide a more concise and efficient way of performing arithmetic or bitwise operations while updating the value of variables.