Assignment and shorthand assignment operator in C

Assignment operator is used to assign value to a variable (memory location). There is a single assignment operator = in C. It evaluates expression on right side of = symbol and assigns evaluated value to left side the variable.

For example consider the below assignment table.

OperationDescription
x = 10Assigns 10 to variable x
y = (5 + 4) / 2Evaluates expression (5+4)/2 and assign result to y
z = x + yEvaluates x + y and assign result to z
5 = xError, you cannot re-assign a value to a constant
10 = 10Error, you cannot re-assign a value to a constant

The RHS of assignment operator must be a constant, expression or variable. Whereas LHS must be a variable (valid memory location).

Shorthand assignment operator

C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator.

For example, consider following C statements.

int a = 5;
a = a + 2;

The above expression a = a + 2 is equivalent to a += 2.

Similarly, there are many shorthand assignment operators. Below is a list of shorthand assignment operators in C.

Shorthand assignment operatorExampleMeaning
+=a += 10a = a + 10
-=a -= 10a = a – 10
*=a *= 10a = a * 10
/=a /= 10a = a / 10
%=a %= 10a = a % 10
&=a &= 10a = a & 10
|=a |= 10a = a | 10
^=a ^= 10a = a ^ 10
~=a ~= 10a = a ~ 10
<<=a <<= 10a = a << 10
>>=a >>= 10a = a >> 10