c中while循环中的复杂三元运算符

  int a = 10;
  while (a > 8 ? (a--, (a > 7 ? a-- : a)): a--,a--) {
    printf("%d", a); // prints out 7
    break;
  }

前提:我知道代码写的很烂,这不是一个真实的例子,我永远不会那样写。

有人可以向我解释为什么它打印 7 而不是 8 吗?似乎最后一个a--是计算出来的,但为什么呢?表达是真的...

回答

逗号运算符的,优先级低于三元运算符?:

打破你的表达:

a > 8 // true because a = 10
  ? (
      a-- // executed, making a 9
      ,
      (
        a > 7 // true because a = 9
          ? a-- // executed, making a 8
          : a // not executed
      )
    )
  : a-- // not executed
,
a-- // executed, making a 7

因此在评估表达式后a变为7


以上是c中while循环中的复杂三元运算符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>