C Assignment Operators
Assignment operators are used to store values inside variables. You have already met the most basic one, the single equals sign =. C also provides a set of shortcut operators that let you update a variable based on its current value using less typing.
The Basic Assignment Operator
The = operator takes the value on its right and stores it in the variable on its left. It always works right to left, so you read x = 5 as store 5 into x.
Assigning a value
#include <stdio.h>
int main() {
int score = 0;
score = 100;
printf("Your score is %d\n", score);
return 0;
}Compound Assignment Operators
Very often you want to change a variable using its own current value, such as adding 5 to a total. C gives you compound operators that combine an arithmetic operation with an assignment. For example, x += 5 is a shorter way of writing x = x + 5.
Using compound assignment
#include <stdio.h>
int main() {
int total = 10;
total += 5; // total is now 15
total *= 2; // total is now 30
printf("Total: %d\n", total);
return 0;
}The program above prints Total: 30. First 5 is added to make 15, then the result is multiplied by 2 to give 30.
- = stores a value into a variable.
- Compound operators like += update a variable using its current value.
- They save typing and make your intent clearer.