Assignment Operators in C ++
Certainly, let's explore assignment operators in C++.
Assignment Operators
In C++, assignment operators are used to assign values to variables. The most basic assignment operator is the = operator.
Basic Assignment (=)
* This operator assigns the value on the right-hand side to the variable on the left-hand side.
int x = 10;
// Assigns the value 10 to the integer variable 'x'
Compound Assignment Operators
C++ provides several compound assignment operators that combine an arithmetic operation with the assignment. These operators make the code more concise and efficient.
* +=: Adds the value on the right-hand side to the variable on the left-hand side and assigns the result to the variable.
x += 5; // Equivalent to x = x + 5;
* -=: Subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result to the variable.
x -= 3; // Equivalent to x = x - 3;
* *=: Multiplies the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.
x *= 2; // Equivalent to x = x * 2;
* /=: Divides the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.
x /= 4; // Equivalent to x = x / 4;
* %=: Calculates the modulus (remainder) of the variable on the left-hand side with the value on the right-hand side and assigns the result to the variable.
x %= 3; // Equivalent to x = x % 3;
* <<=: Performs left shift on the variable on the left-hand side by the number of bits specified on the right-hand side and assigns the result to the variable.
* >>=: Performs right shift on the variable on the left-hand side by the number of bits specified on the right-hand side and assigns the result to the variable.
* &=: Performs bitwise AND operation between the variable on the left-hand side and the value on the right-hand side and assigns the result to the variable.
* |=: Performs bitwise OR operation between the variable on the left-hand side and the value on the right-hand side and assigns the result to the variable.
* ^=: Performs bitwise XOR operation between the variable on the left-hand side and the value on the right-hand side and assigns the result to the variable.
Example
#include <iostream>
int main() {
int num = 10;
num += 5; // num is now 15
num -= 3; // num is now 12
num *= 2; // num is now 24
num /= 4; // num is now 6
std::cout << "num: " << num << std::endl;
return 0;
}
I hope this explanation is helpful! Let me know if you have any further questions.
Comments
Post a Comment