Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?

前端 未结 7 1743
情深已故
情深已故 2020-12-02 20:52

I\'m well aware that in C++

int someValue = i++;
array[i++] = otherValue;

has different effect compared to

int someValue =          


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 21:20

    If we ignore force of habit, '++i' is a simpler operation conceptually: It simply adds one to the value of i, and then uses it.

    i++ on the other hand, is "take the original value of i, store it as a temporary, add one to i, and then return the temporary". It requires us to keep the old value around even after i has been updated.

    And as Konrad Rudolph showed, there can be performance costs to using i++ with user-defined types.

    So the question is, why not always just default to ++i?

    If you have no reason to use `i++´, why do it? Why would you default to the operation which is more complicated to reason about, and may be slower to execute?

提交回复
热议问题