C++ includes several assignment operators that can be used to assign a value to a variable or to perform an operation on a variable and then assign the result to the variable. The most commonly used assignment operators in C++ are:
Basic assignment (=): This operator is used to assign a value to a variable.
Addition assignment (+=): This operator is used to add a value to a variable and then assign the result to the variable.
Subtraction assignment (-=): This operator is used to subtract a value from a variable and then assign the result to the variable.
Multiplication assignment (*=): This operator is used to multiply a variable by a value and then assign the result to the variable.
Division assignment (/=): This operator is used to divide a variable by a value and then assign the result to the variable.
Modulus assignment (%=): This operator is used to calculate the remainder of dividing a variable by a value and then assign the result to the variable.
Left shift assignment (<<=): This operator is used to shift the bits of a variable to the left by a specified number of positions and then assign the result to the variable.
Right shift assignment (>>=): This operator is used to shift the bits of a variable to the right by a specified number of positions and then assign the result to the variable.
Bitwise AND assignment (&=): This operator is used to perform a bit-level AND operation on a variable and a value and then assign the result to the variable.
Bitwise OR assignment (|=): This operator is used to perform a bit-level OR operation on a variable and a value and then assign the result to the variable.
Bitwise XOR assignment (^=): This operator is used to perform a bit-level XOR operation on a variable and a value and then assign the result to the variable.
Here's an example of how these operators can be used:
int x = 5;
int y = 2;
x += y; // x is now 7
x -= y; // x is now 5
x *= y; // x is now 10
x /= y; //x is now 5
x %= y; // x is now 1
x <<= y; // x is now 4
x >>= y; // x is now 1
x &=y; // x is now 0
x |= y; // x is now 2
x ^= y; // x is now 0
Comments
Post a Comment