1

When I do exercises, I always use for loops: for(int i = 0; i < n; i++) But sometimes I got wrong with them, I have tried in many ways to fix, but it ran only when I turn the i++ in for loop to ++i. I wonder when can we use i++ and when ++i?

tryman
  • 3,233
  • 1
  • 12
  • 23
An Nguyen
  • 13
  • 2
  • 1
    Does this answer your question? [Post-increment and Pre-increment concept?](https://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept) – wychmaster Apr 21 '20 at 11:14

3 Answers3

1

i++ and ++i are statements and expressions at the same time.

They both increment the i variable, obviously, and both return the value of i as their result, but i++ returns the value of i before it's incremented whereas ++i returns the value of i after it's incremented.

If you don't use it as an expression but just as a statement, either form works equally well. If you do use the result, it depends what you want to achieve, e.g. in a[i++] = 1 you write to a and then increment the index.

  • 1
    Nitpick: *every* expression can be used as a statement, from the production "[*statement*](https://timsong-cpp.github.io/cppwp/n4659/stmt.stmt): *attribute-specifier-seq* opt [*expression-statement*](https://timsong-cpp.github.io/cppwp/n4659/stmt.expr#nt:expression-statement)" – Caleth Apr 21 '20 at 11:19
1

++i is called pre increment while i++ is called postincrement.

++i increments the value of i and then returns i,
i++ returns the value of i and then increments.

Both of them increase the variable i by one. It's like saying i = i + 1. The difference is subtle. If you're using it in a loop like this, there's no difference:

for (int i = 0; i < 10; i++) {
}

for (int i = 0; i < 10; ++i) {
}
Lakshitha Wisumperuma
  • 1,574
  • 1
  • 10
  • 17
1

Two typical implementations where T represents any type:

++i prefix increment

T& operator++() {   // returns by reference
    // increment *this by 1 here
    return *this;
}

i++ postfix increment

T operator++(int) { // returns by value
    T copy(*this);  // make a copy of the current state
    ++(*this);      // increment *this by 1 here, using the pre-increment operator
    return copy;    // return the copy
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108