Previous | Home | Next |
Assignment Operators
Compound assignment (+=, -=, *=, /=, %=, >>>=, <<=, &=, ^=, |=), when want to change the current stored value of a variable by performing an operation we can use compoundassignment operators:
Expression | Evaluation |
value += increase; | value = value + increase; |
a -= 5; | a = a - 5; |
a /= b; | a = a / b; |
price *= units + 1; | price = price * (units + 1) |
Example
int main () { int a, b=3; a = b; a+=10;// equivalent to a=a+10 printf("\n%d",a ); return 0; }
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.
x = a + b
Here the value of a + b is evaluated and substituted to the variable x. In addition, C has a set of shorthand assignment operators of the form.
Var oper = exp;
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator
Example
x + = 1 is same as x = x + 1
The commonly used Shorthand assignment operators are as follows:
Statement with simple assignment operator | Statement with shorthand operator |
a = a + 1 | a += 1 |
a = a – 1 | a -= 1 |
a = a * (n+1) | a *= (n+1) |
a =a/(n+1) | a /= (n+1) |
a =a % b | a %= b |
Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase. OR Reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
1 | a++; |
2 | a+=1; |
3 | a=+1; |
Previous | Home | Next |