Operators — Arithmetic, Bitwise, Logical, Precedence

সব অপারেটর, বিটের কৌশল ও প্রাধান্য সারণি

~35 min Intermediate 12 practice problems Live code

1. Why This Module Matters

Operators are small symbols, but they carry enormous weight. Most "weird C bugs" come from misunderstanding precedence, integer division, or bitwise nuances. Master this module and half the C pitfalls disappear.

অপারেটর ছোট চিহ্ন হলেও এদের গুরুত্ব বিশাল। C-র বেশিরভাগ অদ্ভুত বাগ আসে precedence, integer division, কিংবা bitwise detail না বোঝা থেকে। এই module আয়ত্ত করলে অর্ধেক সমস্যাই মিটে যাবে।

2. Arithmetic Operators

OpMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23 (integer!)
%Modulo (remainder)7 % 21
++Incrementx++x = x + 1
--Decrementx--x = x − 1
Integer division truncates toward zero. 7 / 2 == 3 এবং -7 / 2 == -3। সঠিক দশমিক ভাগফল পেতে অন্তত একটি operand-কে (double)-এ cast করুন।
Pre- vs Post-Increment
pre_post.c
#include <stdio.h>

int main(void) {
    int x = 5;
    int a = x++;   // post: use then bump (a=5, x=6)
    int b = ++x;   // pre : bump then use (x=7, b=7)
    printf("a = %d, b = %d, x = %d\n", a, b, x);
    return 0;
}

3. Relational & Logical Operators

OpMeaningReturns
==equal1 / 0
!=not equal1 / 0
< > <= >=comparison1 / 0
&&logical AND1 / 0 (short-circuits)
||logical OR1 / 0 (short-circuits)
!logical NOT1 / 0
Short-circuit evaluation A && B-তে A মিথ্যা হলে B কখনো evaluate হয় না। A || B-তে A সত্য হলে B বাদ পড়ে। তাই if (p != NULL && *p == 0) নিরাপদ — null pointer dereference হবে না।
Classic trap if (x = 5) — assignment হয়, comparison নয়! সবসময় == ব্যবহার করুন এবং -Wall flag দিয়ে কম্পাইল করুন — compiler নিজেই এটি ধরিয়ে দেবে।

4. Bitwise Operators — C-র আসল শক্তি

OpMeaningExample
&bitwise AND0b1100 & 0b1010 = 0b1000
|bitwise OR0b1100 | 0b1010 = 0b1110
^bitwise XOR0b1100 ^ 0b1010 = 0b0110
~bitwise NOT~0b1100 = ...11110011
<<left shift1 << 3 = 8
>>right shift16 >> 2 = 4
Famous Bit Tricks — Live Demo
bit_tricks.c
#include <stdio.h>

int main(void) {
    int n = 20;

    // 1. Multiply / divide by powers of two
    printf("20 * 8 (via shift)  = %d\n", n << 3);
    printf("20 / 4 (via shift)  = %d\n", n >> 2);

    // 2. Even or odd?
    printf("20 is even? %s\n", (n & 1) == 0 ? "yes" : "no");

    // 3. Power of two?
    int x = 64;
    printf("%d power of 2? %s\n", x, (x && !(x & (x - 1))) ? "yes" : "no");

    // 4. Swap without temp (XOR trick)
    int a = 5, b = 9;
    a ^= b; b ^= a; a ^= b;
    printf("after XOR swap: a=%d, b=%d\n", a, b);

    // 5. Count set bits (popcount)
    int v = 173, count = 0;
    for (int t = v; t; t >>= 1) count += t & 1;
    printf("set bits in %d = %d\n", v, count);

    return 0;
}
Bitwise কৌশল competitive programming এবং embedded system-এ অস্ত্রের মতো। নিয়মিত অনুশীলন করলে এগুলো স্বাভাবিক হয়ে যাবে।

5. Set / Clear / Toggle / Test a Bit

x |=  (1 << k);    // set bit k
x &= ~(1 << k);    // clear bit k
x ^=  (1 << k);    // toggle bit k
(x >> k) & 1       // test bit k (returns 0 or 1)
flags.c
#include <stdio.h>

#define READ   1   // 0001
#define WRITE  2   // 0010
#define EXEC   4   // 0100

int main(void) {
    int perm = 0;
    perm |= READ;        // grant read
    perm |= WRITE;       // grant write
    printf("perm = %d\n", perm);                 // 3
    printf("can exec? %s\n", (perm & EXEC) ? "yes" : "no");
    perm &= ~WRITE;      // revoke write
    printf("after revoke: %d\n", perm);           // 1
    return 0;
}

6. Compound Assignment

x += 5;    // same as x = x + 5
x -= 3;   x *= 2;   x /= 4;   x %= 7;
x &= mask; x |= flag; x ^= key;
x <<= 1;  x >>= 1;

7. Ternary & Comma Operators

// Ternary: condition ? if_true : if_false
int max = (a > b) ? a : b;

// Comma: evaluate left to right, result = right
for (i = 0, j = 10; i < j; i++, j--) { ... }

8. Precedence & Associativity — The Essential Table

High precedence binds tightest. Within a row, associativity decides order.

LevelOperatorsAssociativity
1 (highest)() [] -> .left
2! ~ ++ -- +x -x *p &x (cast) sizeofright
3* / %left
4+ -left
5<< >>left
6< <= > >=left
7== !=left
8&left
9^left
10|left
11&&left
12||left
13?:right
14= += -= …right
15 (lowest),left
Golden rule যদি সন্দেহ থাকে — parenthesize করুন। (a & 1) == 0 পড়া সহজ এবং বাগ-মুক্ত।

9. Sequence Points & Undefined Behavior

এমন expression কখনো লিখবেন না যেখানে একই variable-কে একই statement-এ একাধিকবার modify করা হয়।

int i = 1;
int x = i++ + i++;          // UB — do not do this
printf("%d %d\n", i++, i++); // UB — order unspecified
একই statement-এ একটি variable-এর মান একাধিকবার পরিবর্তন করবেন না। বরং আলাদা লাইন ব্যবহার করুন।

10. Practice Problems

  1. Predict the output: int a = 5, b = 2; printf("%d %d %d %d %d", a+b, a-b, a*b, a/b, a%b);
    উপরের কোডের output আগে অনুমান করুন, তারপর চালান।
    ✨ Show Answer

    Output: 7 3 10 2 1

    arith.c
    #include <stdio.h>
    int main(void) {
        int a = 5, b = 2;
        printf("%d %d %d %d %d\n", a+b, a-b, a*b, a/b, a%b);
        return 0;
    }
  2. Write int is_even(int n) using bitwise AND.
    Bitwise AND ব্যবহার করে is_even ফাংশন লিখুন।
    ✨ Show Answer
    even.c
    #include <stdio.h>
    int is_even(int n) { return (n & 1) == 0; }
    int main(void) {
        for (int i = 1; i <= 6; i++)
            printf("%d %s\n", i, is_even(i) ? "even" : "odd");
        return 0;
    }
  3. Write int is_power_of_two(int n) in one expression.
    একটি expression-এই is_power_of_two লিখুন।
    ✨ Show Answer
    pow2.c
    #include <stdio.h>
    int is_power_of_two(int n) { return n && !(n & (n - 1)); }
    int main(void) {
        int t[] = {1,2,3,4,5,8,16,17,32,100};
        for (int i = 0; i < 10; i++)
            printf("%3d → %s\n", t[i], is_power_of_two(t[i]) ? "yes" : "no");
        return 0;
    }
  4. Swap two ints without a temp variable using XOR.
    Temp variable ছাড়া XOR দিয়ে দুটি int swap করুন।
    ✨ Show Answer
    xor_swap.c
    #include <stdio.h>
    int main(void) {
        int a = 7, b = 13;
        printf("before: a=%d, b=%d\n", a, b);
        a ^= b; b ^= a; a ^= b;
        printf("after : a=%d, b=%d\n", a, b);
        return 0;
    }
  5. Count the number of set bits in an unsigned int (popcount).
    একটি unsigned int-এ কয়টি bit 1 — সেটি গুনে বের করুন।
    ✨ Show Answer
    popcount.c
    #include <stdio.h>
    int popcount(unsigned int x) {
        int c = 0;
        while (x) { x &= x - 1; c++; }   // Brian Kernighan's trick
        return c;
    }
    int main(void) {
        printf("popcount(173) = %d\n", popcount(173));
        printf("popcount(255) = %d\n", popcount(255));
        return 0;
    }
  6. Given flags READ=1, WRITE=2, EXEC=4, combine, test, and clear bits.
    উপরের flag দিয়ে bit set/clear/test অনুশীলন করুন।
    ✨ Show Answer

    উপরের section 5-এর flags.c-ই সম্পূর্ণ উত্তর।

  7. Without if, compute max(a, b) using the ternary operator.
    if ছাড়া ternary দিয়ে max বের করুন।
    ✨ Show Answer
    max.c
    #include <stdio.h>
    int max(int a, int b) { return (a > b) ? a : b; }
    int main(void) {
        printf("%d\n", max(7, 13));
        printf("%d\n", max(-3, -9));
        return 0;
    }
  8. Why is 1 << 31 undefined behavior for a signed int? How to fix it?
    1 << 31 কেন signed int-এ undefined behavior? সমাধান কী?
    ✨ Show Answer

    ৩২-বিট signed int-এ 1 << 31 sign bit-এ chale যায়, যা C standard অনুযায়ী UB। সমাধান হলো literal 1u ব্যবহার করা — অর্থাৎ 1u << 31 (unsigned)।

  9. Evaluate 3 + 4 * 2 > 10 - 1 && 5 by hand using the precedence table.
    Precedence সারণি ব্যবহার করে হাতে হিসাব করুন।
    ✨ Show Answer

    Step-by-step: 4*2 = 8 → 3 + 8 = 11 → 10 - 1 = 9 → 11 > 9 = 1 → 1 && 5 = 1. ফলাফল: 1।

  10. Write a program that reads an int and prints its binary representation bit by bit.
    একটি int নিয়ে তার binary representation bit-by-bit প্রিন্ট করুন।
    ✨ Show Answer
    print_bits.c — stdin: 42
    #include <stdio.h>
    int main(void) {
        unsigned int x;
        scanf("%u", &x);
        for (int i = 31; i >= 0; i--)
            putchar((x >> i) & 1 ? '1' : '0');
        putchar('\n');
        return 0;
    }
  11. Using x & -x — what does it compute? Test with a few values.
    x & -x কী হিসাব করে? কয়েকটি মান দিয়ে পরীক্ষা করুন।
    ✨ Show Answer

    এটি x-এর সবচেয়ে নিচের set bit (lowest-order 1 bit) বের করে। উদাহরণ: 12 & -12 = 4, 10 & -10 = 2।

    lowbit.c
    #include <stdio.h>
    int main(void) {
        for (int x = 1; x <= 16; x++)
            printf("x=%2d, lowbit=%d\n", x, x & -x);
        return 0;
    }
  12. Classic interview — find the one element that appears once in an array where every other element appears twice. Use XOR.
    Classic interview প্রশ্ন — একটি array-তে সব element দুইবার করে আছে, শুধু একটি element একবার। XOR দিয়ে সেটি বের করুন।
    ✨ Show Answer

    XOR একই সংখ্যা দুইবার করলে 0 হয়। সব element XOR করলে শুধু একবারেরটিই বাকি থাকে।

    single.c
    #include <stdio.h>
    int main(void) {
        int a[] = {4, 1, 2, 1, 2};
        int n = 5, ans = 0;
        for (int i = 0; i < n; i++) ans ^= a[i];
        printf("single element = %d\n", ans);
        return 0;
    }

Glossary (শব্দকোষ)

TermMeaningবাংলায়
OperatorA symbol that performs an operation on values.মানের উপর কাজ করা চিহ্ন।
OperandA value that an operator works on.Operator যে মানের উপর কাজ করে।
Arithmetic Operator+, -, *, /, % — basic math.মৌলিক গণিতের operator।
Relational Operator==, !=, <, >, <=, >= — comparison.তুলনার জন্য ব্যবহৃত operator।
Logical Operator&&, ||, ! — boolean logic.Boolean যুক্তির operator।
Bitwise Operator&, |, ^, ~, <<, >> — work bit-by-bit.Bit-ভিত্তিক operator।
Assignment Operator= and compound forms like +=, *=.= এবং তার যৌগিক রূপ।
Ternary Operatorcond ? a : b — inline if-else expression.Inline if-else expression।
PrecedenceThe order in which operators are evaluated.কোন operator আগে evaluate হবে তার ক্রম।
AssociativityThe direction (left-to-right or right-to-left) for equal-precedence ops.একই precedence-এর operator-এর evaluation দিক।
Short-circuit Evaluation&& and || stop early when result is decided.ফলাফল নিশ্চিত হলেই &&/|| থেমে যায়।
Modulo (%)Remainder after integer division.Integer ভাগের পর অবশিষ্ট।
Increment / Decrement++ and -- — pre and post forms.++ এবং -- — pre/post রূপ।

Summary — Module 07

Arithmetic, relational, logical, bitwise, assignment, ternary, comma — you now have the full operator set. The precedence table is your map. Bitwise tricks are your superpowers. When in doubt, parenthesize. Modify each variable at most once per statement.

সব অপারেটর এক জায়গায় — arithmetic, relational, logical, bitwise, assignment, ternary, comma। Precedence সারণি আপনার map, bitwise কৌশল আপনার অস্ত্র। সন্দেহ হলেই parenthesize করুন। একই statement-এ একটি variable-কে একবারের বেশি পরিবর্তন করবেন না।

Next Module → Input/Output — printf, scanf এবং stream।