Assignment Operators in C

Assignment operators are used to assigning the result of an expression to a variable. Up to now, we have used the shorthand assignment operator “=”, which assigns the result of a right-hand expression to the left-hand variable. For example, in the expression x = y + z, the sum of y and z is assigned to x.

Another form of assignment operator is variable operator_symbol= expression; which is equivalent to variable = variable operator_symbol expression;

We have the following different types of assignment and assignment short-hand operators.

Expression with an assignment operatorDetailed expression with an assignment operator
x += y;x = x + y;
x -= y;x = x – y;
x /= y;x = x / y;
x *= y;x = x * y;
x %= y;x = x % y;
x &= y;x = x & y;
x |= y;x = x | y;
x ^= y;x = x ^ y;
x >>= y;x = x >> y;
x <<= y;x = x << y;
Assignment Operators in C

Examples:

// assignment operators
#include <stdio.h>

int main(){
    int x = 10, y = 15, z = 2, a = 1;

    printf("Value of x before operation is %d\n", x);
    x += 30;
    printf("Value of x after x += 30 is %d\n", x);

    printf("Value of y before operation is %d\n", y);
    y /= z;
    printf("Value of y after y /= z is %d\n", y);

    printf("Value of z before operation is %d\n", z);
    z |= a;
    printf("Value of z after z += a is %d\n", z);

    // analyze the output of bitwise operator

    return 0;
}

Expected Output:

Value of x before operation is 10
Value of x after x += 30 is 40
Value of y before operation is 15
Value of y after y /= z is 7
Value of z before operation is 2
Value of z after z += a is 3