Ternary operator associativity

The ternary operator is left-associative and therefore behaves entirely incorrectly:

$ cat ternary.php <?php echo (FALSE ? "a" : FALSE ? "b" : "c")."

"; echo (FALSE ? "a" : TRUE ? "b" : "c")."

"; echo (TRUE ? "a" : FALSE ? "b" : "c")."

"; echo (TRUE ? "a" : TRUE ? "b" : "c")."

"; ?> $ php ternary.php c b b b

In any other language with a ternary operator, you can stack them and build an if-elseif-elseif-else expression:

$ cat ternary.pl #!/usr/bin/perl -w use strict; print +(0 ? "a" : 0 ? "b" : "c")."

"; print +(0 ? "a" : 1 ? "b" : "c")."

"; print +(1 ? "a" : 0 ? "b" : "c")."

"; print +(1 ? "a" : 1 ? "b" : "c")."

"; $ perl ternary.pl c b a a

$ cat ternary.c #include <stdio.h> int main() { printf("%s

", 0 ? "a" : 0 ? "b" : "c"); printf("%s

", 0 ? "a" : 1 ? "b" : "c"); printf("%s

", 1 ? "a" : 0 ? "b" : "c"); printf("%s

", 1 ? "a" : 1 ? "b" : "c"); } $ gcc -o ternary ternary.c; ./ternary c b a a