Assignment Operators

Which Operator Is Used for Assignment in C?

The operator for assignment in C is the single equals sign, =. Here is how it compares with ==, +=, and other symbols that are easy to mix up.

On this page
  1. The short answer
  2. Symbols that look similar
  3. A common mistake

The short answer

The operator for assignment in C is the single equals sign, =. It stores the value on its right in the variable on its left:

int x = 0;
x = 5;                 /* assignment: x now holds 5 */
x += 2;                /* compound assignment: x now holds 7 */
int same = (x == 5);   /* comparison: same is 0, because x holds 7 */

Symbols that look similar

  • == compares two values. It does not assign anything.
  • := is not an assignment operator in C. Pascal uses := for assignment, and Go uses it to declare a variable and set its value.
  • => is not an operator in C. C# and JavaScript use it for lambda or arrow functions.
  • +=, -=, and similar symbols are compound assignment operators. They combine an operation with assignment.

Comparison is a separate job, and the symbols for it are covered when you ask what operator is used to compare two values.

A common mistake

Putting = where you meant == is a common error in C:

int x = 7;
if (x = 5) {
    /* runs, because x = 5 gives 5, which is not zero */
}

This condition assigns 5 to x and then tests the result, so the body runs and x changes. To compare instead, write if (x == 5). Many compilers warn about the = version when warnings are turned on.

The complete guide to assignment operators

Assignment Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →