Created
April 11, 2013 05:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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