Assignment Operator in C

by | Aug 15, 2021 | C

Assignment Operator in C

The assignment operator in C assigns values of the operand on the right side to the operand on the left side (but this is never done vice versa).

The symbol used for the assignment operator is ‘=’.

As already discussed, a=50; means 50 is assigned to a.

Note: It is not possible to assign any value to a constant. Like ‘4=c’ is not valid and will give an error.

Commonly used assignment operators are:

=’      Assigns the value of right operand to left operand.

+=’   Right operand is added to the left operand, and the result is assigned to the left operand.

‘-=’    Subtracts the value of the right operand from the left operand and assigns the final value to the left operand.

‘*=’   Multiplication between right and left operand is performed first. Then, the result is assigned to the left operand.

‘/=’    Division is performed first. The left operand is divided from the right operand, and the final result is assigned to the left operand.

‘%=’   Finds modulus using two operands, and the result will be assigned to the operator at left.

Example

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

 

Output

Assignment Operator in C

Explanation

Initially, we have ‘a=5’ and ‘b=9’. After evaluating ‘b+=a’, assign 14 to ‘b’. Now, ‘b’ has a value of 14, and ‘b-=a’ results in ‘b=9’. Then, ‘b*=a’ will assign 45 to b since 9*5=45. 45/5=9. Thus, b=9.

In the end, b is 9, and a is 5. So, ‘b%a’ results in ‘b=4’.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.