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

前端 未结 21 2073
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 06:04

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

21条回答
  •  终归单人心
    2020-11-21 06:28

    I assume you understand the difference in semantics now (though honestly I wonder why people ask 'what does operator X mean' questions on stack overflow rather than reading, you know, a book or web tutorial or something.

    But anyway, as far as which one to use, ignore questions of performance, which are unlikely important even in C++. This is the principle you should use when deciding which to use:

    Say what you mean in code.

    If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one version in favor of the other altogether (aka a bone-headed style guide), you should use the form that most exactly expresses what you are trying to do.

    QED, use the pre-increment version:

    for (int i = 0; i != X; ++i) ...
    

提交回复
热议问题