Summary: in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.
Introduction to the C assignment operators
An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:
#include <stdio.h>
int main()
{
int counter;
// assign 1 to counter
counter = 1;
printf("%d\n", counter); // 1
return 0;
}
Code language: C++ (cpp)
After the assignmment, the counter variable holds the number 1.
The following example adds 1 to the counter and assign the result to the counter:
#include <stdio.h>
int main()
{
int counter;
// assign 1 to counter
counter = 1;
// add one to the counter
counter = counter + 1;
printf("%d\n", counter);
return 0;
}
Code language: C++ (cpp)
The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.
Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.
The following example uses a compound-assignment operator (+=):
int x = 5;
x += 10;
Code language: C++ (cpp)
The expression:
x += 10
Code language: C++ (cpp)
is equivalent to the following expression:
x = x + 10;
Code language: C++ (cpp)
The following table illustrates the compound-assignment operators in C:
Operator | Operation Performed | Example | Equivalent expression |
---|---|---|---|
*= | Multiplication assignment | x *= y | x = x * y |
/= | Division assignment | x /= y | x = x / y |
%= | Remainder assignment | x %= y | x = x % y |
+= | Addition assignment | x += y | x = x + y |
-= | Subtraction assignment | x -= y | x = x – y |
<<= | Left-shift assignment | x <<= y | x = x <<=y |
>>= | Right-shift assignment | x >>=y | x = x >>= y |
&= | Bitwise-AND assignment | x &= y | x = x & y |
^= | Bitwise-exclusive-OR assignment | x ^= y | x = x ^ y |
|= | Bitwise-inclusive-OR assignment | x |= y | x = x | y |
Summary
- A simple assignment operator assigns the value of the left operand to the right operand.
- A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.