Assignment operators in C language

To assign a value to a variable, use the assignment operators. The equal sign (=) is a fundamental assignment operator. Compound assignment operators, on the other hand, carry out arithmetic or bitwise operations and then assign the outcome to a variable in a single operation.

Here are the assignment operators in C, along with their shorthand notation:

Operator
Description
Example
=
Simple assignment
x = 5;
+=
Addition assignment
x += 3; (x = x + 3;)
-=
Subtraction assignment
x -= 2; (x = x - 2;)
*=
Multiplication assignment
x *= 4; (x = x * 4;)
/=
Division assignment
x /= 2; (x = x / 2;)
%=
Modulus assignment
x %= 3; (x = x % 3;)
<<=
Left shift assignment
x <<= 2; (x = x << 2;)
>>=
Right shift assignment
x >>= 1; (x = x >> 1;)
&=
Bitwise AND assignment
x &= 7; (x = x & 7;)
^=
Bitwise XOR assignment
x ^= 1; (x = x ^ 1;)
|=
Bitwise OR assignment
x |= 2; (x = x | 2;)

The simple assignment operator (=) assigns the value on the right-hand side to the variable on the left-hand side.

Example:

int x;
x = 5; // x is now 5

Compound assignment operators perform an operation and then assign the result to a variable in a single step.

Example:

int x = 5;
x += 3; // equivalent to x = x + 3; x is now 8
x -= 2; // equivalent to x = x - 2; x is now 6
x *= 4; // equivalent to x = x * 4; x is now 24
x /= 2; // equivalent to x = x / 2; x is now 12
x %= 3; // equivalent to x = x % 3; x is now 0

Bitwise assignment operators perform a bitwise operation and then assign the result to a variable in a single step.

Example:

NOT operator (!)

The NOT operator (!) is used to invert the value of a condition.

Example:

unsigned int x = 0x0A; // binary 00001010
x <<= 2; // equivalent to x = x << 2; x is now 0x28 (binary 00101000)
x &= 0x0F; // equivalent to x = x & 0x0F; x is now 0x08 (binary 00001000)
x ^= 0x03; // equivalent to x = x ^ 0x03; x is now 0x0B (binary 00001011)

Overall, assignment operators are a convenient way to perform an operation and assign the result to a variable in a single step.