Quick links
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.
Operation | Description |
---|---|
x = 10 | Assigns 10 to variable x |
y = (5 + 4) / 2 | Evaluates expression (5+4)/2 and assign result to y |
z = x + y | Evaluates x + y and assign result to z |
5 = x | Error, you cannot re-assign a value to a constant |
10 = 10 | Error, 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 operator | Example | Meaning |
---|---|---|
+= | a += 10 | a = a + 10 |
-= | a -= 10 | a = a – 10 |
*= | a *= 10 | a = a * 10 |
/= | a /= 10 | a = a / 10 |
%= | a %= 10 | a = a % 10 |
&= | a &= 10 | a = a & 10 |
|= | a |= 10 | a = a | 10 |
^= | a ^= 10 | a = a ^ 10 |
~= | a ~= 10 | a = a ~ 10 |
<<= | a <<= 10 | a = a << 10 |
>>= | a >>= 10 | a = a >> 10 |