C++ Assignment Operators

C++ Assignment Operators

Assignment operators in C++ are used to assign values to variables. The basic assignment operator is =, but C++ also offers a set of compound assignment operators that perform an operation and an assignment in a single step.

1. Basic Assignment Operator

Symbol: =

This operator simply assigns the value from the right side of the operator to the left side operand.

int a; a = 5; // a now contains the value 5 

2. Compound Assignment Operators

These operators perform an operation and then assign the result to the left operand.

  • Add and assign: +=

    int a = 5; a += 3; // Equivalent to a = a + 3; now, a is 8 
  • Subtract and assign: -=

    int b = 10; b -= 4; // Equivalent to b = b - 4; now, b is 6 
  • Multiply and assign: *=

    int c = 7; c *= 2; // Equivalent to c = c * 2; now, c is 14 
  • Divide and assign: /=

    int d = 8; d /= 4; // Equivalent to d = d / 4; now, d is 2 
  • Modulus and assign: %=

    int e = 9; e %= 2; // Equivalent to e = e % 2; now, e is 1 
  • Bitwise AND and assign: &=

    int f = 12; // 1100 in binary f &= 10; // 1010 in binary. Now, f is 8 (1000 in binary) 
  • Bitwise OR and assign: |=

    int g = 12; // 1100 in binary g |= 3; // 0011 in binary. Now, g is 15 (1111 in binary) 
  • Bitwise XOR and assign: ^=

    int h = 12; // 1100 in binary h ^= 10; // 1010 in binary. Now, h is 6 (0110 in binary) 
  • Left shift and assign: <<=

    int i = 5; // 0101 in binary i <<= 1; // Now, i is 10 (1010 in binary) 
  • Right shift and assign: >>=

    int j = 5; // 0101 in binary j >>= 1; // Now, j is 2 (0010 in binary) 

Points to Remember:

  • The compound assignment operators provide a shorter syntax when performing operations and assignments simultaneously.

  • The right side of the assignment operator can be a constant value, a variable, or an expression. In the case of an expression, the expression is evaluated first, and then the result is assigned to the variable on the left side.

  • Ensure you understand the difference between = (assignment) and == (equality comparison). Mixing these up is a common source of bugs for beginners.

In conclusion, understanding and using assignment operators efficiently can lead to cleaner and more readable C++ code.


More Tags

sparkr styled-components text-processing google-sheets-query heap-analytics supercsv core char choetl distribution

More Programming Guides

Other Guides

More Programming Examples