📝 C++ Assignment Operators – Assign and Update Values
Assignment operators in C++ are used to assign values to variables — and they can even do some math while they’re at it! 💼📐
📋 Common Assignment Operators
=
– Assign a value+=
– Add and assign-=
– Subtract and assign*=
– Multiply and assign/=
– Divide and assign%=
– Modulus and assign
🔍 Example: Assign and Update
#include <iostream> using namespace std; int main() { int x = 10; x += 5; // x = x + 5 cout << "x after += 5: " << x << endl; x -= 2; // x = x - 2 cout << "x after -= 2: " << x << endl; x *= 3; // x = x * 3 cout << "x after *= 3: " << x << endl; x /= 4; // x = x / 4 cout << "x after /= 4: " << x << endl; x %= 3; // x = x % 3 cout << "x after %= 3: " << x << endl; return 0; }
💡 Why Use Shorthand?
Using +=
, -=
, etc. makes your code shorter and easier to read. It’s like saying “add and update in one shot!” ⚡