Assignment operators are shortcuts. Instead of writing x = x + 5, you can write x += 5. Same result, fewer keystrokes, and once you get used to them, they read more naturally.
The Simple Assignment
The basic = assigns whatever is on the right to whatever is on the left. Simple.
int x = 10;
Compound Assignment Operators
These combine an operation with assignment:
+=— add and assign-=— subtract and assign*=— multiply and assign/=— divide and assign%=— modulus and assign&=— bitwise AND and assign|=— bitwise OR and assign<<=— left shift and assign>>=— right shift and assign
#include
int main() {
int x = 10;
x += 5;
printf("After += 5: %d\n", x);
x -= 3;
printf("After -= 3: %d\n", x);
x *= 2;
printf("After *= 2: %d\n", x);
x /= 4;
printf("After /= 4: %d\n", x);
int y = 7;
y %= 3;
printf("After %%= 3: %d\n", y);
int flags = 5;
flags |= 2;
printf("After |= 2: %d\n", flags);
flags &= 6;
printf("After &= 6: %d\n", flags);
return 0;
}
Try it Yourself →