blog icon indicating copy to clipboard operation
blog copied to clipboard

What is the difference between i++ and ++i in C++?

Open qingquan-li opened this issue 2 years ago • 0 comments

  • i++ will increment the value of i, but return the original value that i held before being incremented.
  • ++i will increment the value of i, and then return the incremented value.
#include <iostream>
using namespace std;

int main() {
    int i = 10;
    int x, y;

    // i++ first assigns a value to expression
    // and then increments the variable.
    x = i++;
    cout << "i is: " << i << endl;
    cout << "x is: " << x << endl;

    cout << endl;

    // ++i first increments
    // then assigns a value to the expression.
    // y = (i += 1);
    y = ++i;
    cout << "i is now: " << i << endl;
    cout << "y is: " << y << endl;

    return 0;
}

Output:

i is: 11
x is: 10

i is now: 12
y is: 12

qingquan-li avatar Jul 06 '22 19:07 qingquan-li