Assignment Operators

Assignment operator is the most used operator in the expression. It is sometimes misinterpreted as equal to operators by beginners. Assignment operator is used to assign value to the variable.






Assignment operator (=)
It is a binary operator where left operand must be a variable.

x=4;

In this expression value 4 is assigned to the variable x.

Following are invalid expressions:

4=x;
3=4;
a+3=5;

Left operand must be a variable.

Compound Assignment Operators(+=, -=, *=, /=, %=)

Example

int main()
{
int x=5;
x+=4; //same as x=x+4
printf("x=%d",x);
return(0);
}

Output is
x=9

Explanation

Expression x+=4 means, x is incremented by 4.

Similarly,

x-=3; is same as x=x-3;
x*=5; is same as x=x*5;
x/=7; is same as x=x/7;
x%=3; is same as x=x%3;

Please do not interpret that the expression x*=2+5 can be simply replaced by x=x*2+5, because there is a difference in priority. To understand this concept observe the following two examples

Example 1
int main()
{
int x=3;
x*=2+5;
printf("x=%d",x);
return(0);
}

Output is
x=21

Explanation

In the expression x*=2+5; operator + has higher priority, thus resolved as x*=7, which further results 21.

Example 2

int main()
{
int x=3;
x=x*2+5;
printf("x=%d",x);
return(0);
}

Output is
x=11

Explanation

In the expression x=x*2+5; operator * has the highest priority, thus the expression is resolved as x=6+5, which is further evaluated as x=11.

Assignment Operators