Skip to content

Instantly share code, notes, and snippets.

@mamantoha
Created November 22, 2012 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamantoha/4129882 to your computer and use it in GitHub Desktop.
Save mamantoha/4129882 to your computer and use it in GitHub Desktop.
Ternary operator associativity
$ cat ternary.c
#include <stdio.h>
int main() {
printf("%s\n", 0 ? "a" : 0 ? "b" : "c");
printf("%s\n", 0 ? "a" : 1 ? "b" : "c");
printf("%s\n", 1 ? "a" : 0 ? "b" : "c");
printf("%s\n", 1 ? "a" : 1 ? "b" : "c");
}
$ gcc -o ternary ternary.c; ./ternary
c
b
a
a
$ cat ternary.pl
#!/usr/bin/perl -w
use strict;
print +(0 ? "a" : 0 ? "b" : "c")."\n";
print +(0 ? "a" : 1 ? "b" : "c")."\n";
print +(1 ? "a" : 0 ? "b" : "c")."\n";
print +(1 ? "a" : 1 ? "b" : "c")."\n";
$ perl ternary.pl
c
b
a
a
$ cat ternary.php
<?php
echo (FALSE ? "a" : FALSE ? "b" : "c")."\n";
echo (FALSE ? "a" : TRUE ? "b" : "c")."\n";
echo (TRUE ? "a" : FALSE ? "b" : "c")."\n";
echo (TRUE ? "a" : TRUE ? "b" : "c")."\n";
?>
$ php ternary.php
c
b
b
b
$ cat ternary.rb
puts false ? "a" : false ? "b" : "c"
puts false ? "a" : true ? "b" : "c"
puts true ? "a" : false ? "b" : "c"
puts true ? "a" : true ? "b" : "c"
$ ruby ternary.rb
c
b
a
a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment