C - Assignment operators

Assignment operators in C are used to assign a value to a variable. They are used to update the value of a variable based on some calculation or operation. In C, the most common assignment operator is the = operator, but there are also compound assignment operators that combine an operation with assignment. Let's illustrate assignment operators in detail with step-by-step examples:

Simple Assignment Operator (=)

The simple assignment operator (=) is used to assign a value to a variable.


#include <stdio.h>

int main() {
    int x;      // Declare an integer variable
    x = 5;       // Assign the value 5 to the variable x

    printf("x = %d\n", x); // Output: x = 5

    return 0;
}

In this example, we declare an integer variable x and then assign the value 5 to it using the = operator.

Compound Assignment Operators

Compound assignment operators combine an operation with assignment. They perform an operation on the variable and then assign the result back to the variable. Common compound assignment operators include +=, -=, *=, /=, and %=.

Addition and Assignment (+=)

#include <stdio.h>

int main() {
    int x = 5;
    x += 3;  // Equivalent to x = x + 3

    printf("x = %d\n", x); // Output: x = 8

    return 0;
}

In this example, x += 3 is equivalent to x = x + 3. It adds 3 to the current value of x and assigns the result back to x.

Subtraction and Assignment (-=)

#include <stdio.h>

int main() {
    int x = 10;
    x -= 4;  // Equivalent to x = x - 4

    printf("x = %d\n", x); // Output: x = 6

    return 0;
}

Here, x -= 4 subtracts 4 from the current value of x and assigns the result back to x.

Multiplication and Assignment (*=)

#include <stdio.h>

int main() {
    int x = 7;
    x *= 2;  // Equivalent to x = x * 2

    printf("x = %d\n", x); // Output: x = 14

    return 0;
}

x *= 2 multiplies the current value of x by 2 and assigns the result back to x.

Division and Assignment (/=)

#include <stdio.h>

int main() {
    int x = 16;
    x /= 4;  // Equivalent to x = x / 4

    printf("x = %d\n", x); // Output: x = 4

    return 0;
}

In this case, x /= 4 divides the current value of x by 4 and assigns the result back to x.

Modulus and Assignment (%=)

#include <stdio.h>

int main() {
    int x = 17;
    x %= 5;  // Equivalent to x = x % 5

    printf("x = %d\n", x); // Output: x = 2

    return 0;
}

x %= 5 calculates the remainder when the current value of x is divided by 5 and assigns the result back to x.

These compound assignment operators are convenient and efficient ways to perform an operation and update a variable's value in a single step.