Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 135 ยท Operators

Assignment and Increment Operators

Learn C's assignment operators: = as an expression, compound assignment like += and <<=, prefix vs postfix ++ and --, and why i = i++ is undefined behavior.

Programs constantly change values: a counter goes up by one, a total grows by the next price, a balance shrinks by a withdrawal. C has a compact set of operators for exactly this: plain assignment =, ten compound assignment operators such as += and *=, and the famous increment and decrement operators ++ and --, which gave C++ its name.

These operators are short, and that's both their strength and their danger. In this lesson you'll learn what each one does, the difference between ++i and i++, why assignment is an expression with a value of its own, and the one rule that keeps code like i = i++ out of your programs.

Assignment is an expression

x = 5 stores 5 in x. The left side must be something that designates a storage location, called an lvalue: a variable, an array element a[i], a dereferenced pointer *p, or a struct member s.field. 5 = x doesn't compile, and neither does assigning to a whole array (int a[3], b[3]; a = b; is an error; copy arrays with a loop or memcpy).

Unlike in many languages, assignment in C is an expression: it has a value, namely the value that was stored, with the type of the left side. Two common idioms rely on that.

Chained assignment. Assignment groups right to left, so a = b = c = 0 means a = (b = (c = 0)): zero is stored in c, then that value is stored in b, then in a.

Assign and test in one step. The classic character-reading loop stores the result of getchar() and compares it with EOF in the same condition:

C Assignment inside a loop condition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The parentheses around (c = getchar()) are essential. != binds tighter than =, so without them c = getchar() != EOF would store the comparison result (0 or 1) in c. Note also that c is an int: getchar returns either a character value or EOF, which is negative, and a char can't reliably hold both. Reading Input with scanf and fgets covers this loop in detail.

Because assignment is an expression, if (x = 5) compiles. It stores 5 in x and then tests 5, which is always true. With -Wall, GCC warns: suggest parentheses around assignment used as truth value. When you really mean assign-and-test, write the extra parentheses and an explicit comparison, as in while ((c = getchar()) != EOF). The if, else if and else lesson shows more = versus == bugs.

Compound assignment

Updating a variable with its own old value is so common that C has a shortcut for each binary arithmetic and bitwise operator:

Operator Equivalent to Operator Equivalent to
x += y x = x + y x &= y x = x & y
x -= y x = x - y x |= y x = x | y
x *= y x = x * y x ^= y x = x ^ y
x /= y x = x / y x <<= y x = x << y
x %= y x = x % y x >>= y x = x >> y

Two details make compound assignment more than just shorthand:

  1. The right side is evaluated as a whole first. x *= y + 1 means x = x * (y + 1), not x = x * y + 1.
  2. The left side is evaluated only once. In counts[next_index()] += 1, the function is called once. If you wrote counts[next_index()] = counts[next_index()] + 1, it would be called twice, possibly with different results.

There is also a silent conversion to watch. The result is converted back to the type of the left side, so int variables lose fractions: total += 2.7 adds 2.7 in floating point and then truncates the result. GCC doesn't warn about this with -Wall -Wextra; only -Wconversion does.

C Compound assignment in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The bitwise forms such as |= and ^= are the everyday tools for flags; they're explained in Bitwise Operators.

Increment and decrement: ++ and --

++ adds one to a variable and -- subtracts one. Each comes in two forms, and when the operator is a statement on its own, the two forms do the same thing:

C
count++;   // count = count + 1
++count;   // the same

The difference shows up when you use the value of the expression:

  • Prefix ++i increments first and gives the new value.
  • Postfix i++ gives the old value, and the increment takes effect as a side effect.
C Prefix versus postfix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

squares[n++] = ... is idiomatic C: "put the value at the next free position, then move the position along". You'll meet its pointer cousin *p++ in Pointer Arithmetic.

In a for loop's update part (value++ above) the value isn't used, so i++ and ++i compile to identical code. Pick one style and stick with it; C programmers mostly write i++.

++ and -- work on any arithmetic type, including double and char, and on pointers, where they move to the next or previous element. They need an lvalue: 5++ and (x + 1)++ don't compile.

The rule: don't modify a variable twice in one expression

Here is where the compact operators get dangerous. What should these lines do?

C
i = i++;                        // undefined behavior
a[i] = i++;                     // undefined behavior
printf("%d %d\n", n++, n++);    // undefined behavior
x = ++y + y;                    // undefined behavior

Each one modifies a variable and also reads or modifies it again in the same expression, without anything that orders the two. C doesn't evaluate expressions strictly left to right; the compiler may compute the parts of an expression, and apply the side effects of ++, in whatever order is fastest. The standard therefore says: if a scalar object is modified twice, or modified and also read for a different purpose, and the two accesses are unsequenced, the behavior is undefined. The program may print one result today and another with different optimization flags, and it's allowed to do anything else too.

Older books explain this with sequence points: moments in a program where all earlier side effects are complete. C11 replaced that wording with "sequenced before", but the practical points are the same:

  • The end of a full expression (usually the ;) completes all side effects.
  • &&, ||, ?: and the comma operator each evaluate their left side completely before the right side.
  • All arguments are evaluated before a function is called, but in no particular order relative to each other. The commas between function arguments are separators, not comma operators.

GCC catches the simple cases with -Wall. The next example compiles with a warning on purpose; read the message rather than the output, which is not guaranteed:

C The compiler warns about i = i++

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The warning is operation on 'i' may be undefined [-Wsequence-point]. Compilers can't detect every case, especially when pointers are involved (*p = (*q)++ is undefined if p and q point to the same variable), so the real defense is a habit: use ++ and -- either as a statement on their own or in a simple, well-known idiom like a[n++] = value, and never on a variable that appears elsewhere in the same expression.

Unspecified order also affects function calls that have side effects. In total = read_number() - read_number();, C doesn't say which call happens first, so the result can differ between compilers. That isn't undefined behavior, just unspecified, but it's still a bug. Store each result in its own variable first.

Assignment to const and other things that don't compile

A few rules round out the picture:

  • A const variable can be initialized but never assigned: const int max = 10; max = 11; is an error (see Constants).
  • Initialization looks like assignment but isn't one: int x = 5; gives x its first value as part of the declaration. That's why const variables and arrays can be initialized (int a[3] = {1, 2, 3};) even though they can't be assigned.
  • Struct variables can be assigned as a whole (p1 = p2; copies every member), unlike arrays. You'll see this in Structures.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int x = 4; int y = x++ * 2; printf("%d %d", x, y);

    The postfix x++ yields the old value 4, so y is 8. The increment still happens, so x is 5 afterward.
  2. 2. With int x = 3, y = 2;, what is x after x *= y + 1;?

    The whole right side is evaluated first, so the statement means x = x * (y + 1), which is 3 * 3.
  3. 3. Why is int c (not char c) used in while ((c = getchar()) != EOF)?

    EOF is a negative int distinct from every unsigned char value. Storing the result in a char can make a real character look like EOF, or make EOF never match.
  4. 4. Which line has well-defined behavior?

    In a[i++] = 0, i is read once to form the index and modified once, which is fine. The other lines modify a variable and read or modify it again without ordering, which is undefined.
  5. 5. What value does the expression (n = 7) have?

    Assignment is an expression whose value is the value stored (with the type of the left side). That is why chained assignment and assign-and-test loops work.

Summary

  • = stores a value in an lvalue and is itself an expression whose value is the stored value; that enables a = b = 0 and while ((c = getchar()) != EOF).
  • Compound assignment (+= -= *= /= %= &= |= ^= <<= >>=) evaluates the whole right side first and the left side only once, then converts the result to the left side's type.
  • ++i increments and yields the new value; i++ yields the old value. As standalone statements they are identical.
  • Modifying a variable twice, or modifying and reading it, in one expression without sequencing (i = i++, a[i] = i++) is undefined behavior. Function arguments are evaluated in an unspecified order.
  • Keep ++ and -- in their own statements or in well-known idioms such as a[n++] = value.

Next: Comparison and Logical Operators