05. Assignment Operators & Compound Assignments

🟢 Difficulty: Beginner | Simple Assignment, Compound Mutators & Value Expressions

📖 Definition

An assignment operator stores the evaluated result of a right-hand expression into the memory location specified by a left-hand modifiable lvalue (variable or dereferenced pointer). C provides the simple assignment operator = and a full suite of compound assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=).

🎯 Why It Is Used

  • Concise In-Place Mutation: x += 5 is cleaner and avoids re-evaluating complex lvalue expressions compared to x = x + 5.
  • Lvalue Expression Safety: In compound assignments like array[compute_index()] += 10, the lvalue array expression compute_index() is evaluated exactly once.

⚙️ How It Works: Assignment Expressions Return Values

In C, an assignment operation is an expression that returns the assigned value. This allows chained assignments like a = b = c = 10; (which evaluates right-to-left as a = (b = (c = 10));).

📝 Syntax & Compound Assignment Operators

Compound Operator Equivalent Expansion Sample Usage (x=10) New Value of x
x += yx = x + yx += 515
x -= yx = x - yx -= 37
x *= yx = x * yx *= 220
x /= yx = x / yx /= 42
x %= yx = x % yx %= 31
x &= yx = x & yx &= 62
x |= yx = x | yx |= 414
x ^= yx = x ^ yx ^= 100
x <<= yx = x << yx <<= 240
x >>= yx = x >> yx >>= 15

🔀 Lvalues vs Rvalues

The left side of an assignment operator must be an lvalue (a memory location that can be assigned to, such as a non-const variable name or *ptr). Literals like 10 = x or expressions like (a + b) = 5 are invalid rvalues and generate compiler errors.

🌱 Beginner Example

#include <stdio.h>

int main(void) {
    int score = 50;
    printf("Initial score: %d\n", score);

    score += 25; // Equivalent to score = score + 25
    printf("Score after bonus (+25): %d\n", score);

    score *= 2;  // Equivalent to score = score * 2
    printf("Score after multiplier (*2): %d\n", score);
    return 0;
}

🌼 Intermediate Example: Chained Assignments & Stream Loops

#include <stdio.h>

int main(void) {
    int x, y, z;
    // Chained assignment sets x, y, and z to 100 in one line
    x = y = z = 100;
    printf("x = %d, y = %d, z = %d\n", x, y, z);

    int ch;
    printf("Enter characters (Ctrl+D/Ctrl+Z to exit): ");
    // Idiomatic assignment expression inside while loop condition
    while ((ch = getchar()) != EOF && ch != '\n') {
        printf("[%c]", ch);
    }
    printf("\n");
    return 0;
}

🌲 Advanced Example: Single-Evaluation Security Guarantee of Compound Assign

#include <stdio.h>

int get_index(void) {
    static int idx = 0;
    printf("[Side Effect Log] get_index called -> returning %d\n", idx);
    return idx++;
}

int main(void) {
    int balances[3] = {100, 200, 300};

    // Compound assignment evaluates 'get_index()' EXACTLY ONCE!
    balances[get_index()] += 50;

    printf("Balances after compound assignment: %d, %d, %d\n",
           balances[0], balances[1], balances[2]);
    return 0;
}

🔍 Line-by-Line Explanation

  • x = y = z = 100;: Evaluates right-to-left: z=100 returns 100, assigning it to y, which returns 100, assigning it to x.
  • while ((ch = getchar()) != EOF): The assignment ch = getchar() returns the read integer value, which is then compared against EOF.
  • balances[get_index()] += 50;: Compound assignment evaluates the array index expression get_index() only once, updating balances[0] from 100 to 150 safely.

💻 Expected Terminal Output

x = 100, y = 100, z = 100
[Side Effect Log] get_index called -> returning 0
Balances after compound assignment: 150, 200, 300

⚠️ Common Mistakes & Pitfalls

  • Confusing Assignment = with Equality ==: Writing if (status = 1) inside a conditional executes the assignment and always evaluates to true! Always use ==.
  • Assigning to Const Variables: Attempting const int x = 5; x += 2; causes a compilation error because x is not a modifiable lvalue.

📌 Important Rules & Limitations

  • The left operand must be a modifiable lvalue.
  • Assignment operators have right-to-left associativity.

🌐 Multilingual Explanation: English

Assignment operators assign right-hand expressions to left-hand lvalues. Compound operators (+=, *=, &=) perform in-place mutation while evaluating the left-hand lvalue address exactly once.

🌐 Multilingual Explanation: Hindi (Roman Script)

Assignment operator = value store karta hai. Compound operators (+=, -=, *=) code ko chota aur clean banate hain, jaise x += 5 equivalent hai x = x + 5 ke.

🌐 Multilingual Explanation: Marathi (Roman Script)

Assignment operator = value save karto. Compound operators (+=, -=) in-place mutation kartat. if condition madhye = aani == chukavu naka.

❓ Practice Questions

  1. Why is arr[get_index()] += 5 safer than arr[get_index()] = arr[get_index()] + 5?
  2. In what order does the chained assignment a = b = c = 5; evaluate?
  3. What is an lvalue in C?

🚀 Practical Coding Challenge

Write a program named running_stats.c that prompts a user for numbers in a loop. Accumulate the total using +=, update the count using += 1, and print the updated average after each entry until the user enters 0.

🧭 Navigation & Breadcrumbs

← Previous: 04. Bitwise Operators | Module 05 Guide | Next: 06. Increment & Decrement Operators →