Prerequisite – Operators in C
In C, assignment operators are used to assign a value to a variable. They combine the assignment operation (=) with an arithmetic, bitwise, or other operation. Here are the assignment operators in C:
List of Assignment Operators in C:
| Operator | Example | Equivalent to |
|---|---|---|
| = | a = b | a = b |
| += | a += b | a = a + b |
| -= | a -= b | a = a – b |
| *= | a *= b | a = a * b |
| /= | a /= b | a = a / b |
| %= | a %= b | a = a % b |
| <<= | a <<= b | a = a << b |
| >>= | a >>= b | a = a >> b |
| &= | a &= b | a = a & b |
| ^= | a ^= b | a = a ^ b |
| |= | a |= b | a = a | b |
Example:
Here’s an example code that demonstrates the use of assignment operators in C:
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
printf("a = %d, b = %d\n", a, b);
a += b;
printf("a += b: %d\n", a);
a -= b;
printf("a -= b: %d\n", a);
a *= b;
printf("a *= b: %d\n", a);
a /= b;
printf("a /= b: %d\n", a);
a %= b;
printf("a %%= b: %d\n", a);
a <<= b;
printf("a <<= b: %d\n", a);
a >>= b;
printf("a >>= b: %d\n", a);
a &= b;
printf("a &= b: %d\n", a);
a ^= b;
printf("a ^= b: %d\n", a);
a |= b;
printf("a |= b: %d\n", a);
return 0;
}
When you run this code, you will see the following output:
a = 10, b = 20 a += b: 30 a -= b: 10 a *= b: 200 a /= b: 10 a %= b: 10 a <<= b: 10240 a >>= b: 20 a &= b: 20 a ^= b: 0 a |= b: 20
This output shows the results of using each of the assignment operators with the variables a and b. The value of a changes after each operation, and the result is printed to the console.
Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.
