DMD 0.149 release
Georg Wrede
georg.wrede at nospam.org
Wed Mar 8 02:49:22 PST 2006
Chris Miller wrote:
> On Tue, 07 Mar 2006 19:47:38 -0500, Georg Wrede
> <georg.wrede at nospam.org> wrote:
>
>> but more like
>>
>> bool x = strcmp("foo", "bar");
>> if (!x) { /* do stuff */ } // match
>> else { /* call the cops! */ } // no match
>
> You shouldn't even be doing that! You're inverting the meaning of true
> and false. Use int.
Yeah, I know. (In hindsight, in this NG, maybe I should have tried to
find a C function that returns 0 on failure. :-) )
Then again it's supposed to be easy to use C from D, and there are a lot
of functions that return int values such that zero signifies true and
anything else signifies false, and, one is also supposed to be able to
use the particular [nonzero] return value for other purposes. (Call this
old school efficiency or whatever, but as long as we are supposed to use
C libraries, that's what we'll have to live with.)
>> Now what happens to
>>
>> if (stcmp("foo", "bar")) {}
>
>
> If this wasn't allowed I'd be furious.
I bet you wouldn't be alone!
In the first example, the reason for using bool was to be explicit about
*not* intending to use the value for other than true/false, otherwise of
course an int would be used instead.
Admittedly,
bool x = strcmp("foo", "bar");
is bad code. Inverted meaning of x, and also a nonobvious name for a
boolean variable. Better would be
bool areDifferent = strcmp("foo", "bar");
(which unfortunately doesn't compile on 0.149), or better
bool stringsMatch = ! strcmp("foo", "bar");
but this would have diverted the point of the example, since the "!"
makes the code compilable!
For C functions that return int to signify truth value, one now (as of
0.149) has to do a cast. That becomes cumbersome if one has to do a lot
of C library usage. It also makes the code less readable.
Seems there are two options
bool a,b,c,d;
a = cast(bool) strcmp("foo", "bar");
b = cast(bool) strcmp("foo", "baf");
c = cast(bool) strcmp("foo", "bag");
d = cast(bool) strcmp("foo", "bad");
or the newly found "cast to bool operator", brought up by BCS (in
D.announce 3032)
a = !! strcmp("foo", "bar");
b = !! strcmp("foo", "baf");
c = !! strcmp("foo", "bag");
d = !! strcmp("foo", "bad");
This is certainly less typing, and it shrouds less the original code. If
it weren't for this discovery, I'd have a *hard time* living with this
last change in D.
So the "!!" might become a much used idiom in D now. I wonder what the
reaction from the C++ crowd will be.
---
(Aside:) In real code of course, one should never invert booleans, and
one should always use variable names with semantic content for the
reader. Thus, one probably would write something like
bool match;
match = ! strcmp("foo", "bar");
if (match)
{
/* do stuff */
}
else
{
/* call the cops! */
}
More information about the Digitalmars-d-announce
mailing list