Operators in C | Assignment Operator

Assignment Operators

The following table lists the assignment operators supported by the C language −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B
will assign the value of A + B to C

a=10
b=a;
c=b;
result:
a=10
b=10
c=10

#include<stdio.h>
int main()
{
	int a,b,c;
	a=10;
	b=20;
	c=a+b;
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	printf("Sum = %d\n",c);
	return(0);
}

Output:

a = 10
b = 20
Sum = 30
Operator Description Example
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

C += A is equivalent to C = C + A

1.
int a,b,c;
a=10
a+=10; /* a=a+10; */
result:
a=20

2.
int a=10,b=20;
a+=10; /* a=a+10; */
b+=a; /* b=b+a; */
result:
a=20;
b=40;

#include<stdio.h>
int main()
{
	int a,b,c;
	a=10;
	printf("a = %d\n",a);
	a+=10;  /* a=a+10 */
	printf("a = %d\n",a);
	return(0);
}

Output:

a = 10
a = 20
#include<stdio.h>
int main()
{
	int a=10,b=20;
	a+=10; /* a=a+10; */
	b+=a; /* b=b+a; */
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	return(0);
}

Output:

a = 20
b = 40
Operator Description Example
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.

C -= A is equivalent to C = C – A

1.
int a,b,c;
a=20
a-=10; /* a=a-10; */
result:
a=10

2.
int a=20,b=20;
a-=10; /* a=a-10; */
b-=a; /* b=b-a; */
result:
a=10;
b=10;

#include<stdio.h>
int main()
{
	int a=20,b=20;
	a-=10; /* a=a-10; */
	b-=a; /* b=b-a; */
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	return(0);
}

Output:

a = 10
b = 10
Operator Description Example
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.

C *= A is equivalent to C = C * A

#include<stdio.h>
int main()
{
	int a=20,b=20;
	a*=5; /* a=a*10; */
	b*=10; /* b=b*10; */
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	return(0);
}

Output:

a = 100
b = 200
Operator Description Example
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.

C /= A is equivalent to C = C / A

#include<stdio.h>
int main()
{
	int a=20,b=20;
	a/=5; /* a=a/10; */
	b/=10; /* b=b/10; */
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	return(0);
}

Output:

a = 4
b = 2
Operator Description Example
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.

C %= A is equivalent to C = C % A

#include<stdio.h>
int main()
{
	int a=20,b=20;
	a%=3; /* a=a%3; */
	b%=7; /* b=b%7; */
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	return(0);
}

Output:

a = 2
b = 6