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.

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

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>