← Back to C Course | Chapter 3: Operators | Lesson 6 of 9

C Assignment Operators

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 (=)

c
#include <stdio.h>
int main() {
	int x;
	x = 10;
	printf("%d", x);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int total = 10;
	total += 5;
	total -= 2;
	printf("%d", total);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	float price = 100;
	price *= 1.1f;
	printf("%.2f", price);
	return 0;
}

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 (%=)

c
#include <stdio.h>
int main() {
	int index = 7;
	index %= 5;
	printf("%d", index);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int flags = 6;
	flags &= 3;
	printf("%d", flags);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.