Tim Woodall said:
As an aside:
I recall seeing some platform specific headers which went for the
all-bits-one representation of "true" -- but the C implementations
gave 1 for !!TRUE as well...
int is_it_seven(int x)
{
return x==7;
}
if(is_it_seven(7) == TRUE)
printf("7 is seven\n");
else
printf("7 is not seven\n");
While I would never write the explicit test for TRUE [1], I would be
horrified at any header that defined TRUE such that this code didn't
behave as expected.
[1] Other peoples coding standards excepted.
The way to avoid this problem is to avoid *ever* doing an equality or
inequality comparison against either TRUE or FALSE. It happens that
FALSE can only be 0 (assuming sanity on the part of the author), so
(whatever == FALSE) is probably safe, but it's easier to remember and
follow the more general rule.
Remember that the is*() functions in <ctype.h> are explicitly allowed
to return non-zero values, so even with TRUE defined as 1, the test
(isalpha(c) == TRUE) is broken.
If you're going to define FALSE and TRUE, there's no reason to use
values other than FALSE==0 and TRUE==1. (Note that C99's <stdbool.h>
has false==0 and true==1.) But if you're going to write
if (is_it_seven(7) == TRUE) ...
you might as well write
if (((is_it_seven(7) == TRUE) != FALSE) == TRUE) ...
Or just do it right:
if (is_it_seven(7)) ...
There's no reason why one unnecessary comparison is better than two or
more. There's only one logical place to stop adding comparisons, and
that's before the first one.
The relational operators are defined to yield 0 or 1; if they don't,
the compiler is broken. But code that depends on this, though valid,
is suspicious; it's too easy to change
count += (x == 42);
to
count += (nearly_equal(x, 42));
and miss the fact that nearly_equal can return -1.
[...]
If you are using sign-magnitude or ones complement encoding then the
possible values of a signed int bitfield will be +0 and -0 or 0 and a
trap representation.
(I hope there isn't something somewhere that says that bitfields must be
twos complement. I can't see it but I'm sure if there is someone here
will be along quickly to correct me. ;-) )
No, bit fields aren't required to be two's complement, so there's no
guarantee that a 1-bit signed bit field can hold a value other than 0.
But signed bit fields in general are unlikely to be useful. That's
not to say that they're never useful. If you want a struct member to
be as small as possible and to hold any value in the range -7..+7, a
4-bit signed bit field is the way to do it. But as soon as you try to
store -8, you've lost some portability. (Then again, a restriction to
2's-complement systems may not be a problem.)