Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

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

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago
#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