The assignment operators are used to assign value to a variable. For example, if we want to assign a value 10 to a variable x
then we can do this by using the assignment operator like: x = 10;
Here, =
(equal to) operator is used to assign the value.
In the C language, the =
(equal to) operator is used for assignment however it has several other variants such as +=
, -=
to combine two operations in a single statement.
You can see all the assignment operators in the table given below.
Operator | Description | Example(a and b are two variables, with where a=10 and b=5) |
---|---|---|
= | assigns values from right side operand to left side operand | a=b , a gets value 5 |
+= | adds right operand to the left operand and assign the result to left operand | a+=b , is same as a=a+b , value of a becomes 15 |
-= | subtracts right operand from the left operand and assign the result to left operand | a-=b , is same as a=a-b , value of a becomes 5 |
*= | mutiply left operand with the right operand and assign the result to left operand | a*=b , is same as a=a*b , value of a becomes 50 |
/= | divides left operand with the right operand and assign the result to left operand | a/=b , is same as a=a/b , value of a becomes 2 |
%= | calculate modulus using two operands and assign the result to left operand | a%=b , is same as a=a%b , value of a becomes 0 |
When we combine the arithmetic operators with the assignment operator =
, then we get the shorthand form of all the arthmetic operators.
Example: Using Assignment Operators
Below we have a code example in which we have used all the different forms of assignment operator, starting from the basic assignment.
#include <stdio.h>
int main() {
int a = 10;
// Assign
int result = a;
printf("result = %d \n",result);
// += operator
result += a;
printf("result = %d \n",result);
// -= operator
result -= a;
printf("result = %d \n",result);
// *= operator
result *= a;
printf("result = %d \n",result);
return 0;
}
Output
result = 10 result = 20 result = 10 result = 100