Archana Anbazhagan
PRO
2 months ago
Archanacountry asked

Why do we use increment and decrement operators in C++?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hi Archana,

We use increment (++) and decrement (--) operators in C++ to quickly increase or decrease a variable's value by 1. They're mainly used for:

  1. Simpler code
    Instead of writing i = i + 1, you can just write i++. It’s shorter and easier to read.

  2. Looping
    These operators are commonly used in loops. For example:

    for (int i = 0; i < 5; i++) {
        cout << i << " ";
    }
    

    This loop prints: 0 1 2 3 4

  3. Prefix vs Postfix

    • ++i (prefix) increases the value before it’s used

    • i++ (postfix) uses the value first, then increases it

    Example:

    int i = 5;
    cout << ++i; // Outputs 6  
    cout << i++; // Outputs 6, then i becomes 7
    

Both forms are useful depending on when you want the increment or decrement to happen.

If you have more questions, I’m here to help.

C++
This question was asked as part of the Learn C++ Basics course.