Assignment Operators in C with Examples

🧠 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 assigna += 5;a = a + 5;
-=Subtract and assigna -= 3;a = a - 3;
*=Multiply and assigna *= 2;a = a * 2;
/=Divide and assigna /= 4;a = a / 4;
%=Modulus and assigna %= 3;a = a % 3;
&=Bitwise AND and assigna &= 2;a = a & 2;
|=Bitwise OR and assigna |= 1;a = a | 1;
^=Bitwise XOR and assigna ^= 3;a = a ^ 3;
<<=Left shift and assigna <<= 1;a = a << 1;
>>=Right shift and assigna >>= 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”

assignment operators in c, c programming assignment operator, compound assignment operators, c operator examples, c programming tutorial, learn c language, beginner c tutorial, c code with explanation, programming basics in c, c programming operators list, c language examples, use of = in c, c programming for students, coding in c, computer science assignment c

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন