1

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.
}
lucmobz
  • 151
  • 1
  • 6
  • Why do you use the comma expression there? – Some programmer dude Jan 06 '22 at 18:21
  • Because otherwise the compiler gives me an error `lvalue required as left operand of assignment` which I am still investigating (at least one of the commas has to stay). – lucmobz Jan 06 '22 at 18:27
  • Which turned out to be another matter of operator precedence. Putting parens around it fixed it. `a < b ? c = 1 : (d = 1);` – lucmobz Jan 06 '22 at 18:29
  • 2
    That you need to jump through so many hoops to get it right is a clear indicator that the conditional expression isn't really the best solution here. Why not a plain `if else` statement? Which is more readable, clearer, more maintainable, and much harder to get wrong. – Some programmer dude Jan 06 '22 at 18:49
  • You are right, I was doing an exercise and wanted to see if it was possible and got stuck into this precedence problem. – lucmobz Jan 06 '22 at 19:04

1 Answers1

4

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

(a < b ? c, c = 1 : d), d = 1;
Brian Bi
  • 111,498
  • 10
  • 176
  • 312