CAssignment Operators

Assignment Operators

The plain assignment operator = 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.

C
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

+=

x += 5;

x = x + 5;

-=

x -= 5;

x = x - 5;

*=

x *= 5;

x = x * 5;

/=

x /= 5;

x = x / 5;

%=

x %= 5;

x = x % 5;

&=

x &= 5;

x = x & 5;

|=

x |= 5;

x = x | 5;

^=

x ^= 5;

x = x ^ 5;

<<=

x <<= 1;

x = x << 1;

>>=

x >>= 1;

x = x >> 1;

C
#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.

C
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 0
The Classic = vs == Bug
if (x = 5) compiles — and is always true
This is one of the most infamous bugs in C. Writing a single = 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.

C
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");
}
Compiling with warnings enabled catches this class of bug. GCC and Clang will flag a bare assignment used as a condition when built with -Wall (specifically the -Wparentheses warning), suggesting you wrap the assignment in extra parentheses if it was intentional.

Bash
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 assignment

  • Assignment is an expression and associates right-to-left, enabling a = b = c = 0;

  • Never write if (x = 5) when you mean if (x == 5) — always compile with -Wall to catch it