C++

How to use Subtraction Assignment (-=) Operator in C++

The subtraction assignment operator (-=) performs the two-step computation in one step. As from the name, it subtracts the value of the right-side variable and assigns the outcome to the left-side variable. This tutorial will make you understand the compound assignment -= operator in C++ with some examples.

What is Subtraction Assignment Operator in C++

The subtraction assignment operator (-=) performs mathematical tasks in one step only, which minimizes the complexity of the program and improves its efficiency. The syntax of the subtraction assignment (-=) operator:

value1 -= value2;

The value can be an operand or any type of data value. As value1 -= value 2 works like value1-value2 and save the result to value1. Let’s look at program examples in C++ that utilize the “-=” operator.

Example 1

The C++ program is defined below in a very simple way:

#include <iostream>

using namespace std;

 

int main() {

  int a = 10;

  a -= 2;

  cout << "Value of a using (-=) Operator: " << a << endl;

}

In this code, the subtraction assignment operator is utilized to take a variable with a starting value of 10, subtract from it a value of 2, and then saved the result to a. So, the output showed the new value of variable 8:

Example 2

Following is another example of using subtraction assignment operator with conditional statements:

#include <iostream>

using namespace std;

int main() {

  int a = 20;

  cout << "The initial value of a is: " << a << endl;

  a -= 10;

  if (a == 10) {

    cout<< "After using Subtraction assignment operator a Value = " <<a<< endl;

  } else {

    cout<< "Invalid" << a << endl;

  }

  return 0;

}

Here, the integer variable a is initialized with a 20 starting value. To subtract 10 from a, we utilize the -= operator. After performing the subtraction operation, we then use an if-else statement to determine if the value of a is equal to 10. The message After using the Subtraction Assignment operator a Value = is printed followed by the value of an if the condition is true. If not, we display the error message Invalid, which is the value of a. The output on the screen will be as follows:

Conclusion

The compound assignment operators are the combination of two combined operators. In this tutorial, we have explained the -= compound assignment operator that is highly useful to get a difference between two variables of the opposite sides of = and allocate the outcome to the left side variable in only a single step. The above article also elaborated on the subtraction assignment operator example program of C++ with simple integer datatype and if-else statement.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.