i was just playing around with the ternary operator in my c class today. And found this odd behavior.
#include <stdio.h>
#include <stdbool.h>
main()
{
int x='0' ? 1 : 2;
printf("%i",x);
}
returns 1 as expected.But
#include <stdio.h>
#include <stdbool.h>
main()
{
int x='0'==true ? 1 : 2;
printf("%i",x);
}
returns 2 while i expect it to return 1.
The value of ‘0’ is not zero, it is whatever integer value encodes the digit ‘0’ on your system. Typically 48 (in encodings borring from ASCII), which is then not equal to
truewhen interpreted as an integer, which is 1.So the first of your code lines is equivalent to
which clearly evaluates to
1. The second iswhich just as clearly evaluates to
2.