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;