【问题标题】:c++ for loop post-increment pre-increment differencec++ for循环后自增前自增差异
【发布时间】:2017-11-11 03:02:14
【问题描述】:

我一直在寻找答案,但我越来越困惑。

我有这两个 for 循环

for (int i = 1; (i < 5) && move.from[i - 1]; i++) {
    int const departurePoint = move.from[i - 1];
    int arrivalPoint = move.to[i - 1];

    if (arrivalPoint < 0) { // A blot was hit
        arrivalPoint = -arrivalPoint;
        board[1 - turn][BAR - arrivalPoint]--; // Remove the blot
        board[1 - turn][BAR]++; // and place it on the bar */
    }

    board[turn][departurePoint]--; // Move our own checker
    board[turn][arrivalPoint]++; // to it's landing spot.
}

for (int i = 1; (i < 5) && move.from[i - 1]; ++i) {
    int const departurePoint = move.from[i - 1];
    int arrivalPoint = move.to[i - 1];

    if (arrivalPoint < 0) { // We hit a blot
        arrivalPoint = -arrivalPoint;
        board[1 - turn][BAR - arrivalPoint]++; // Replace the blot
        board[1 - turn][BAR]--; // remove it from the bar
    }

    board[turn][departurePoint]++; // Replace our own checker
    board[turn][arrivalPoint]--; // to it's original spot.
}

我的问题是:

  1. 在带有预增量的for循环语句中,当计算“move.from[i - 1]”时,i是否被递增?
  2. 我是否在语句正文中增加了?

【问题讨论】:

标签: c++ for-loop


【解决方案1】:
for (int i = 1; (i < 5) && move.from[i - 1]; i++ /*i increments here and nowhere else*/)

for (int i = 1; (i < 5) && move.from[i - 1]; ++i /*i increments here and nowhere else*/)

两个代码是等价的。差别很小,不适用于本例。

i==3

++i 表示: 4=i+1=(++i) 然后i=4

i++ 表示: 3= i =(i++) 然后i=4

除非你将它分配给另一个变量,否则它不会产生影响:

for(...; ...; k=i++)

for(...; ...; k=++i)

i+1 表示:

i 存储到临时变量中。将临时变量加一。它读取i,但不写入ii 只会在 ++--i= 以及其他一些情况下发生变化。

【讨论】:

  • 好的。那这不就一样了吗? for (int i = 0; (i
  • @helgovic,不。在您的情况下,++ii++ 是相同的。不使用增量的结果。在增量之后检查条件(i &lt; 5)。因此,它不关心i++++i
【解决方案2】:

您的简短问题是i++++i 之间的区别是表达式的值吗?

i++的值是i在增量前的值++i的值是i在递增后的值

示例:

int i = 2;
std::cout << i++ << std::cout; // shows 2
std::cout << i << std::cout; // shows 3

i = 2;
std::cout << ++i << std::cout; // shows 3
std::cout << i << std::cout; // shows 3

i----i 运算符的工作方式相同。

【讨论】:

    【解决方案3】:

    for 循环有两个语句和一个这样的表达式:

    for(init_statement;condition_expresion;progress_statement){
     //...body...
    }
    

    这条指令的语义和写法基本一致:

    init_statement;
    while(condition_expresion){
      //...body...
      progress_statement;
    }
    

    注意i++++i 的副作用是一样的,变量i 加一。这两条指令在用作表达式时是不同的,i++ 计算为递增前的 i 的值,++i 计算为递增后的值。这与 for 循环无关,因为进程语句的值被丢弃了。

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多