C Assignment Operator

In C, the Assignment = operator is used to assign a value to a variable. It stores the right-hand side (RHS) value into the left-hand side (LHS) variable.

The Assignment Operator can also be used in combination with arithmetic and bitwise operators to perform compound assignments.


Syntax of the Assignment Operator

The syntax to use the Assignment Operator is:

</>
Copy
variable = value;

Explanation:

  1. variable: The left-hand operand that stores the assigned value.
  2. =: The assignment operator, which assigns the RHS value to the LHS variable.
  3. value: The right-hand operand that provides the value to be assigned.

Examples of the Assignment Operator

1. Assigning a Value to a Variable

In this example, we will assign an integer value to a variable using the Assignment Operator and print the result.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num;
    num = 10; // Assigning value

    printf("The value of num is: %d\n", num);
    return 0;
}

Explanation:

  1. We declare an integer variable num.
  2. The statement num = 10; assigns the value 10 to num.
  3. We print the value of num using printf().

Output:

The value of num is: 10

2. Chained Assignment

In this example, we will use chained assignment to assign a single value to multiple variables in a single statement.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int a, b, c;
    
    a = b = c = 20; // Chained assignment

    printf("a = %d, b = %d, c = %d\n", a, b, c);
    return 0;
}

Explanation:

  1. We declare three integer variables: a, b, and c.
  2. The statement a = b = c = 20; assigns the value 20 to all three variables.
  3. Since assignment returns the assigned value, c = 20 assigns 20 to c, then b = c assigns 20 to b, and finally, a = b assigns 20 to a.
  4. We print the values of a, b, and c using printf().

Output:

a = 20, b = 20, c = 20

3. Using Assignment with Arithmetic Operations

In this example, we will use the Assignment Operator with arithmetic operations to modify a variable’s value.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int x = 5;
    x = x + 10; // Arithmetic assignment

    printf("The new value of x is: %d\n", x);
    return 0;
}

Explanation:

  1. We declare an integer variable x and initialize it to 5.
  2. The statement x = x + 10; increases x by 10 and stores the result back in x.
  3. We print the updated value of x using printf().

Output:

The new value of x is: 15

Conclusion

In this tutorial, we covered the Assignment Operator = in C. The important points to remember are:

  1. The Assignment Operator is used to assign values to variables.
  2. It can be used for simple assignments, chained assignments, and arithmetic operations.
  3. The Assignment Operator returns the assigned value, allowing assignment chaining.