C Assignment Operators
In this page:
Simple Assignment (=)
= stores the value on its right side into the variable on its left -- the most basic operation in C, and distinct from == which compares two values instead of assigning one, a mix-up that causes many subtle bugs.
Example: Simple Assignment (=)
#include <stdio.h>
int main() {
int x;
x = 10;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Add (+=) and Subtract (-=) Shorthands
+= and -= are shorthand for adding or subtracting a value and immediately storing the result back into the same variable, so total += 5; is exactly equivalent to total = total + 5; but shorter to write and read.
Example: Add (+=) and Subtract (-=) Shorthands
#include <stdio.h>
int main() {
int total = 10;
total += 5;
total -= 2;
printf("%d", total);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiply (*=) and Divide (/=) Shorthands
*= and /= work the same shorthand way for multiplication and division -- price *= 1.1; applies a 10% increase to price in place, without needing to repeat the variable name on both sides of the expression.
Example: Multiply (*=) and Divide (/=) Shorthands
#include <stdio.h>
int main() {
float price = 100;
price *= 1.1f;
printf("%.2f", price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modulo Assignment (%=)
%= divides the variable by a value and stores the remainder back into that same variable -- useful for things like keeping a rotating counter within a fixed range, such as wrapping an index back to 0 after reaching an array's size.
Example: Modulo Assignment (%=)
#include <stdio.h>
int main() {
int index = 7;
index %= 5;
printf("%d", index);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bitwise Assignment Shorthands
C also provides &=, |=, ^=, <<=, and >>= as shorthand for applying a bitwise operation and reassigning the result in one step -- the same read-modify-write pattern as += and -=, just for bit-level operations instead of arithmetic.
Example: Bitwise Assignment Shorthands
#include <stdio.h>
int main() {
int flags = 6;
flags &= 3;
printf("%d", flags);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: