Compound Assignment Operators in C++

C++Server Side ProgrammingProgramming

The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −

  • An arithmetic type
  • A pointer, if op is + or –

The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once.

The following are the compound assignment operators in C++ −

Operators
Description
*=
Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
/=
Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
%=
Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand.
+=
Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand.
–=
Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand.
<<=
Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
>>=
Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
&=
Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand.
^=
Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand.
|=
Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand.

Example

Let's have a look at an example using some of these operators −

#include<iostream>
using namespace std;

int main() {
   int a = 3, b = 2;

   a += b;
   cout << a << endl;

   a -= b;
   cout << a << endl;

   a *= b;
   cout << a << endl;

   a /= b;
   cout << a << endl;

   return 0;
}

Output

This will give the output −

5
3
6
3

Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.

raja
Published on 15-Feb-2018 16:48:05
Advertisements