Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The comma operator has lower precedence than the conditional operator, so your expression is equivalent to:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading