Skip to content

Instantly share code, notes, and snippets.

@jdavis
Created April 11, 2013 05:18
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 jdavis/5360942 to your computer and use it in GitHub Desktop.
Save jdavis/5360942 to your computer and use it in GitHub Desktop.
Code sample showing the wonkiness of the precedence of the ternary statement in C.
#include <stdio.h>
char identity(char x);
int main(int argc, const char *argv[]) {
int compound;
printf("For reference:\n");
printf(" the ASCII value of %c is %d\n", ';', ';');
printf(" the ASCII value of %c is %d\n", '}', '}');
printf("\n");
/*
* Bad.
*/
compound = 0;
printf("Should be falsy. Actually is %d\n", identity('}') != compound ? ';' : '}');
compound = 1;
printf("Should be truthy: Actually is %d\n", identity('}') != compound ? ';' : '}');
compound = 0;
printf("Should be truthy. Actually is %d\n", identity(';') != compound ? ';' : '}');
compound = 1;
printf("Should be falsy: Actually is %d\n", identity(';') != compound ? ';' : '}');
printf("\n");
/*
* What actually is happening based on precedence rules.
*/
(identity('}') != compound) ? ';' : '}';
/*
* What you want.
*/
identity('}') != (compound ? ';' : '}');
/*
* Good.
*/
compound = 0;
printf("Should be falsy. Actually is %d\n", identity('}') != (compound ? ';' : '}'));
compound = 1;
printf("Should be truthy: Actually is %d\n", identity('}') != (compound ? ';' : '}'));
compound = 0;
printf("Should be truthy. Actually is %d\n", identity(';') != (compound ? ';' : '}'));
compound = 1;
printf("Should be falsy: Actually is %d\n", identity(';') != (compound ? ';' : '}'));
/*
* Output:
For reference:
the ASCII value of ; is 59
the ASCII value of } is 125
Should be falsy. Actually is 59
Should be truthy: Actually is 59
Should be truthy. Actually is 59
Should be falsy: Actually is 59
Should be falsy. Actually is 0
Should be truthy: Actually is 1
Should be truthy. Actually is 1
Should be falsy: Actually is 0
*/
return 0;
}
char identity(char x) {
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment