Assignment operators
- C course
- Beginner
- Lesson 25/116
- 4 min
Learn shortcut assignments with =, +=, -=, *=, /= and ++/--.
Assignment and compound assignment
The = operator assigns the right value to the left variable. +=, -=, *=, /= are compound assignment: they do the operation and the assignment together.
int x = 10;
x += 5; /* x = x + 5 → 15 */
x -= 3; /* x = x - 3 → 12 */Compound assignment reduces repetition and keeps code short. x += 5 means the same as x = x + 5.
Increment and decrement
++ raises a variable by one, -- lowers it by one. They have two forms: post-increment x++ and pre-increment ++x.
int x = 5;
int y = x++; /* y = 5, x = 6 */
int z = ++x; /* z = 7, x = 7 */x++ returns the old value then increments; ++x increments first then returns the new value. Used alone, both behave the same.
Practice Compound assignment and increment
Define int x = 10;. Add 5 with x += 5;. Subtract 3 with x -= 3;. Increment by one with x++;. Then print x with printf("%d\n", x);. Output should be 13.
Starter code
#include <stdio.h>
int main(void) {
int x = 10;
/* add 5, subtract 3, increment and print */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int x = 10;
x += 5;
x -= 3;
x++;
printf("%d\n", x);
return 0;
}Expected output
13
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Compound assignment operator
int x = 10;
x____= 5; /* x is now 15 */
int x = 10;
x+= 5; /* x is now 15 */
Explanation: x += 5 is the same as x = x + 5.
2 What is the difference between x++ and ++x?
- No difference
- x++ increments first
- x++ returns the value first Correct answer
- Both are compile errors
Explanation: x++ returns the value first then increments (post-increment).
3 Match assignment operators
| Term | Meaning |
|---|---|
= |
direct assignment |
+= |
add and assign |
-= |
subtract and assign |
++ |
increment by one |