Reputation: 1965
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
.
Upvotes: 1
Views: 173
Reputation: 183251
That's because (assuming ASCII) '0'
represents the integer 0x30
, i.e. 48
, and true
represents the integer 1
. So they're not equal.
In C, any nonzero value is considered true, but true
itself is 1
, and 1
is what you get from any built-in Boolean test (for example, 0 == 0
is 1
).
Upvotes: 1
Reputation: 145829
Maybe you are confusing '\0'
and '0'
The value of the character constant
'\0'
is always 0
in C.
The value of the character constant
'0'
is implementation defined and depends on the character set. For ASCII, it is 0x30
.
Also note that the macro true
is defined to the value 1
and not 0
.
Upvotes: 1
Reputation: 89055
'0'
does not equal true
, so the result of '0'==true
is 0 (false). This is assigned to x
and passed to the ternary operator, giving the result you see.
If you intended something else, you should use brackets to clarify the order of precedence you want, or break your code up into multiple statements.
Upvotes: 0
Reputation: 399763
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 true
when interpreted as an integer, which is 1.
So the first of your code lines is equivalent to
int x = (48 != 0) ? 1 : 2;
which clearly evaluates to 1
. The second is
int x = (48 == 1) ? 1 : 2;
which just as clearly evaluates to 2
.
Upvotes: 2
Reputation: 86651
That's because '0' != true
. The boolean value gets promoted to an integer type and is equal to 1 whereas '0'
is equal to 48
Upvotes: 0
Reputation: 47493
true
is defined as 1. '0'
in ASCII is 0x30 which is not equal to 1.
Therefore the condition '0'==true
is not true.
Upvotes: 0