简体   繁体   English

C 三元算子分支评测?

[英]C ternary operator branches evaluation?

I always assumed the ternary operator in C did not evaluate the branch that failed the test.我一直假设C中的三元运算符没有评估未通过测试的分支。 Why does it in this case?为什么在这种情况下呢? a is less than b so only c should be assigned to 1 , d should remain 2 . a小于b所以只有c应该分配给1d应该保持2 Thank your for tips and suggestions.感谢您的提示和建议。 I have compiled with both gcc-9 and clang.我用 gcc-9 和 clang 编译。

#include <stdio.h>

int main() {
  int a = 42;
  int b = 99;
  int c = 0;
  int d = 2;

  // Both branches are evaluated?
  a < b ? c, c = 1 : d, d = 1;

  printf("c %d, d %d.\n", c, d);
  // Prints c 1, d 1.
}

The comma operator has lower precedence than the conditional operator, so your expression is equivalent to:逗号运算符的优先级低于条件运算符,因此您的表达式等效于:

(a < b ? c, c = 1 : d), d = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM