Assignment operators: =, +=, -=, *=, /=

Home / C Programming / Assignment operators: =, +=, -=, *=, /=

Assignment operators: =, +=, -=, *=, /=


Assignment operators in C programming are used to assign values to variables. They provide a shorthand way to perform an operation and assign the result to the variable on the left-hand side. Here are the assignment operators in C:

1. Assignment (=):

The `=` operator assigns the value on the right-hand side to the variable on the left-hand side.

   Example:

   int num = 5;  // Assigns the value 5 to the variable num

2. Addition assignment (+=):

The `+=` operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result to the variable.

   Example:

   int num = 5;

   num += 3;  // Equivalent to num = num + 3; num becomes 8


3. Subtraction assignment (-= ):

The `-=` operator subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result to the variable.

   Example:

   int num = 5;

   num -= 3;  // Equivalent to num = num - 3; num becomes 2

4. Multiplication assignment (*=):

The `*=` operator multiplies the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.

   Example:

   int num = 5;

   num *= 3;  // Equivalent to num = num * 3; num becomes 15

5. Division assignment ( /= ):

The `/=` operator divides the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.

   Example:

   int num = 10;

   num /= 3;  // Equivalent to num = num / 3; num becomes 3 (integer division truncates decimal part)

Assignment operators provide a convenient way to modify the value of a variable by performing an operation and assigning the result in a single step. They are often used in loops, calculations, and other scenarios where the value of a variable needs to be updated.

Example:

int num = 5;

num += 2;  // num becomes 7

num *= 3;  // num becomes 21

num /= 7;  // num becomes 3 (integer division)

Assignment operators provide a concise way to update variable values based on calculations or other operations in your C programs.