blog
blog copied to clipboard
What is the difference between i++ and ++i in C++?
-
i++
will increment the value ofi
, but return the original value thati
held before being incremented. -
++i
will increment the value ofi
, 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