C++ Compound Assignment Operators

www.igif‮t‬idea.com

C++ provides compound assignment operators that combine an arithmetic or bitwise operation with an assignment operation. They provide a shorthand way to perform an operation on a variable and assign the result back to the same variable. Here are the compound assignment operators:

  1. Addition and Assignment: +=
x += y; // equivalent to x = x + y;
  1. Subtraction and Assignment: -=
x -= y; // equivalent to x = x - y;
  1. Multiplication and Assignment: *=
x *= y; // equivalent to x = x * y;
  1. Division and Assignment: /=
x /= y; // equivalent to x = x / y;
  1. Modulus and Assignment: %=
x %= y; // equivalent to x = x % y;
  1. Bitwise AND and Assignment: &=
x &= y; // equivalent to x = x & y;
  1. Bitwise OR and Assignment: |=
x |= y; // equivalent to x = x | y;
  1. Bitwise XOR and Assignment: ^=
x ^= y; // equivalent to x = x ^ y;
  1. Left Shift and Assignment: <<=
x <<= y; // equivalent to x = x << y;
  1. Right Shift and Assignment: >>=
x >>= y; // equivalent to x = x >> y;

In summary, compound assignment operators provide a shorthand way to perform an arithmetic or bitwise operation and assign the result back to the same variable. They can help to make code shorter and more readable.