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

前端 未结 21 2077
伪装坚强ぢ
伪装坚强ぢ 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:06

    They both increment the number. ++i is equivalent to i = i + 1.

    i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

    Example:

    int i = 1;
    int x = i++; //x is 1, i is 2
    int y = ++i; //y is 3, i is 3
    

提交回复
热议问题