【问题标题】:What happens when there is multiple expressions in the condition part of a for loop seperated by commas?当 for 循环的条件部分中有多个用逗号分隔的表达式时会发生什么?
【发布时间】:2014-08-17 06:45:48
【问题描述】:

我这里有一个无限循环,但是为什么?

int end = 5;
for(int i = 0; i < end, printf("at condition i=%d\n",i); ++i) 
{
    printf("inside i=%d\n",i);
}

【问题讨论】:

标签: c loops syntax comma-operator


【解决方案1】:

逗号运算符的左操作数作为空表达式求值,逗号运算符的求值结果是右操作数的结果。因此,for 循环的“if”部分查看printf 的结果,该结果大于零,这意味着它永远不会结束。

您可以通过交换它们来修复它:

int end = 5;
for(int i = 0; printf("at condition i=%d\n",i), i < end; ++i) 
{
    printf("inside i=%d\n",i);
}

但最好不要这样做。它的可读性不是很好。

【讨论】:

  • -1 这与关联性无关,与逗号运算符的工作方式有关,C11 6.5.17 "The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value"
  • @Lundin 谢谢,我把条款搞砸了,我更新了我的答案。
【解决方案2】:

逗号运算符表达式i &lt; end, printf("at condition i=%d\n",i) 用作条件。它的值是它的右操作数,也就是printf的返回值。

printf 的返回值是它输出的字符数,在这种情况下永远不会为零,所以它是一个无限循环。

【讨论】:

    【解决方案3】:

    您需要了解comma operator。逗号表达式的结果是右操作数的结果。在控制表达式i &lt; end, printf("at condition i=%d\n",i) 中,对i &lt; end 求值并丢弃其结果。
    因此,循环由表达式 printf("at condition i=%d\n",i) 的值控制,该表达式返回它打印的字符数,因此它在此处始终评估为 true 并导致无限循环。

    【讨论】:

      【解决方案4】:

      如果用-Wall编译,

      warning: left-hand operand of comma expression has no effect
      

      所以i &lt; end 无效。 printf() 返回它打印的字符数。
      根据返回值(此处为非零值),发生无限循环。

      【讨论】:

        【解决方案5】:

        因为

        1) i &lt; end, printf("at condition i=%d\n",i) 返回与printf("at condition i=%d\n",i) 相同的值。

        2) printf() 返回打印字符数(在这种情况下不为零)

        所以循环中的条件始终为真。

        【讨论】:

          【解决方案6】:

          在表达式i &lt; end, printf("at condition i=%d\n")中,逗号操作符使得两个表达式依次求值,但是第一个表达式的结果被丢弃,只使用printf的结果来控制循环。由于printf 将始终为该格式字符串返回非零值,因此循环永远不会终止。

          改用&amp;&amp;

          for (int i = 0; i < end && printf("at condition i=%d\n"); i++)
          

          【讨论】:

            猜你喜欢
            • 2020-04-23
            • 1970-01-01
            • 1970-01-01
            • 2023-04-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-01
            • 1970-01-01
            相关资源
            最近更新 更多