🧠 Assignment Operators in C
Assignment operators are used to assign values to variables. The most common operator is =. There are also compound assignment operators that combine operations like addition, subtraction, etc., with assignment.
✅ Basic Assignment Operator: =
This assigns the value on the right to the variable on the left.
#include <stdio.h>
int main() {
int a;
a = 10; // Assign 10 to a
printf("Value of a: %d\n", a);
return 0;
}
🔁 Compound Assignment Operators
These combine an arithmetic or bitwise operation with assignment:
| Operator | Description | Example | Equivalent |
|---|---|---|---|
| += | Add and assign | a += 5; | a = a + 5; |
| -= | Subtract and assign | a -= 3; | a = a - 3; |
| *= | Multiply and assign | a *= 2; | a = a * 2; |
| /= | Divide and assign | a /= 4; | a = a / 4; |
| %= | Modulus and assign | a %= 3; | a = a % 3; |
| &= | Bitwise AND and assign | a &= 2; | a = a & 2; |
| |= | Bitwise OR and assign | a |= 1; | a = a | 1; |
| ^= | Bitwise XOR and assign | a ^= 3; | a = a ^ 3; |
| <<= | Left shift and assign | a <<= 1; | a = a << 1; |
| >>= | Right shift and assign | a >>= 2; | a = a >> 2; |
💻 Example Code for Compound Assignment
#include <stdio.h>
int main() {
int a = 10;
a += 5;
printf("a += 5 => %d\n", a);
a -= 3;
printf("a -= 3 => %d\n", a);
a *= 2;
printf("a *= 2 => %d\n", a);
a /= 4;
printf("a /= 4 => %d\n", a);
a %= 5;
printf("a %%= 5 => %d\n", a);
a = 6;
a &= 3;
printf("a &= 3 => %d\n", a);
a |= 1;
printf("a |= 1 => %d\n", a);
a ^= 2;
printf("a ^= 2 => %d\n", a);
a <<= 2;
printf("a <<= 2 => %d\n", a);
a >>= 1;
printf("a >>= 1 => %d\n", a);
return 0;
}
📝 Summary
=assigns a value to a variable.- Compound operators save time and space in code.
- They are common in loops and calculations.
📌 Next Topic Suggestion: “Relational and Logical Operators in C”
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন