What is /= Operator in C++?
The /= operator is a called compound assignment operator in the C++ programming language that combines division and assignment into a single operation. This operator divides the left-side variable by the right-side variable and after this stores the result to the left-side variable as mentioned in the below syntax:
The above expression a /= b is equal to a = a / b in C++.
It’s necessary to keep in mind that the /= operator’s functionality can vary based on the operands’ data types. For example, if every operand is an integer, the division result will also be an integer, eliminating any fractional portions of the result. On the other hand, the outcome of a division will be a number that is floating point with full precision if at least one of the operands is a floating-point number. Let’s demonstrate this by using program examples in C++.
Example 1: Using /= Operator with Integer Data Type
In this example, we implement the divide and assignment operator in a single step and all the operands are integer-type data:
using namespace std;
int main() {
int num1 = 10;
int num2 = 5;
cout << "Value of num1 = " << num1 << endl;
num1 /= num2;
cout << "Value of num1 using /= operator = " << num1 << endl;
return 0;
}
First, we initialized both integer variables num1 and num2 in this program to 10 and 5, respectively. Then, we divided num1 by num2, using the /= operator, causing num1 to be altered to 2. Finally, we used another cout statement to send the modified value of num1 to the console.
The output from this program should look something like this:
Example 2: Using /= Operator with Float Data Type
In C++ the division assignment operator is implemented in this example in a single step, and all the variables are float data types:
using namespace std;
int main() {
float num1 = 10.0;
float num2 = 2.3;
cout << "Value of num1 = " << num1 << endl;
num1 /= num2;
cout << "Value of num1 using /= operator = " << num1 << endl;
return 0;
}
In this example, we declared two floating-point variables as num1 and num2, with initialized values of 10.0 and 2.3, respectively. We then use the /= operator to divide num1 by num2 and assigned the result back to num1. The result is printed using cout.
The output value of num1 before num1 is 10 after using the /= operator num1 becomes 4 as shown below:
Conclusion
C++ is a very versatile general-purpose language that is very simple and easy to use. It has many predefined operators, one of which is the division assignment operator. The division assignment operator is represented by /= and is helpful to update the variable value. In the above tutorial, we have seen the functionality of the division assignment operator in C++. The /= operator result varies according to the data type of variables provided in the C++ program.