Assignment Operators
= stores the value of its right-hand side into the variable on its left. C also provides a family of compound assignment operators that combine an arithmetic or bitwise operation with assignment in a single, shorter step.int x; x = 10; // basic assignment: x now holds 10
Compound Assignment Operators
Each compound operator below is shorthand for "take the variable, apply the operator with the right-hand value, and store the result back into the variable".
Operator | Example | Equivalent to |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#include <stdio.h>
int main(void) {
int x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2
printf("%d\n", x); // 2
return 0;
}Chained Assignment
Assignment is itself an expression that evaluates to the value that was assigned, and it associates right-to-left. That means multiple variables can be initialized to the same value in a single statement.
int a, b, c;
a = b = c = 0; // evaluated right-to-left: c = 0, then b = (c), then a = (b)
printf("%d %d %d\n", a, b, c); // 0 0 0The Classic = vs == Bug
= inside an if condition does not compare — it assigns. The expression x = 5 stores 5 into x and then evaluates to 5, which is nonzero and therefore always truthy. The branch runs every time, and x has silently been overwritten. This compiles cleanly with no error, which is what makes it so dangerous.int x = 0;
/* BUG: assignment instead of comparison — always true, and x becomes 5 */
if (x = 5) {
printf("this always runs\n");
}
/* CORRECT */
if (x == 5) {
printf("this only runs when x is really 5\n");
}-Wall (specifically the -Wparentheses warning), suggesting you wrap the assignment in extra parentheses if it was intentional.gcc -Wall -o prog prog.c # prog.c:4:10: warning: suggest parentheses around assignment used as # truth value [-Wparentheses]
=stores a value; the compound operators combine an operation with assignmentAssignment is an expression and associates right-to-left, enabling
a = b = c = 0;Never write
if (x = 5)when you meanif (x == 5)— always compile with-Wallto catch it