简体   繁体   中英

C ternary operator branches evaluation?

I always assumed the ternary operator in C did not evaluate the branch that failed the test. Why does it in this case? a is less than b so only c should be assigned to 1 , d should remain 2 . Thank your for tips and suggestions. I have compiled with both gcc-9 and 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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