C++ Increment/Decrement

🔄 C++ Increment and Decrement Operators Explained Simply

Increment (++) and Decrement (--) are unary operators used to increase or decrease a value by 1. These are handy when looping or counting things in code – no need for calculators! 🔢

🚀 Types of Increment/Decrement

  • Prefix: ++x or --x – changes the value before it’s used.
  • Postfix: x++ or x-- – changes the value after it’s used.

🔧 Example: Prefix vs Postfix

#include <iostream>
using namespace std;

int main() {
    int x = 5;

    cout << "x: " << x << endl;

    cout << "Prefix ++x: " << ++x << endl;  // x becomes 6, then printed
    cout << "Postfix x++: " << x++ << endl;  // x printed as 6, then becomes 7
    cout << "After postfix, x: " << x << endl;

    cout << "Prefix --x: " << --x << endl;  // x becomes 6, then printed
    cout << "Postfix x--: " << x-- << endl;  // x printed as 6, then becomes 5
    cout << "After postfix, x: " << x << endl;

    return 0;
}

Try It Now

🎯 Why Use These?

They’re perfect for:

  • Loops – like for and while
  • Counters – tracking steps, scores, etc.
  • Simplifying code – less typing, more logic!

Whether you’re counting up or counting down, ++ and -- make coding a breeze! 🌬️