On Mon, Oct 30, 2017 at 01:51:30PM -0600, Jonathan M Davis via Digitalmars-d 
wrote:
> On Monday, October 30, 2017 11:04:32 Steven Schveighoffer via Digitalmars-d 
> wrote:
[...]
> > TBH, I don't think I ever considered doing if(floatingpointvalue) to
> > be a good idea in C or D. I generally stay away from float, and
> > especially comparing to 0 directly.
> 
> Yeah. Honestly, I stay away from if(x) in general if x isn't a bool. I
> might occasionally do it for a pointer, but it's not like floating
> point types are the only ones that act badly with cast(bool) (e.g.
> dynamic arrays). It all works just fine if you understand what each of
> the types do with cast(bool), but it's just clearer if you make the
> check it explicit.

+1 for writing it explicitly.  It reminds me of C code along these
lines:

        if (some_function(x)) {
                cleanup();
                return ERROR;
        }
        if (some_other_function(y)) {
                return SUCCESS;
        }

Typical result of the widespread C convention of returning int that can
mean ... basically anything.  Some functions return 0 to mean error,
some return 0 to mean success, and of course, on the caller's side you
assume clairvoyance on the part of the would-be reader of your code to
know what was intended.

Which leads to fun (or insanity) like this:

        int f(char *s, int x) {
                return strcmp(s, "verbose") && !printf("The result is ")
                        || x && !printf("success ") || isalnum(x) &&
                        !printf("unknown ") || printf("(%d)", x) &&
                        printf("\n");
        }


Back in D land, I was so happy way back when, when dmd began rejecting
this code:

        S* sp;
        while ((sp = getS()) && someCondition) { ... }

and I had to write this instead:

        S* sp;
        while ((sp = getS()) !is null && someCondition) { ... }

Added a whole new level of readability to my code.

Nowadays, I don't even like using implicit conversions to bool anymore.
Intent is much better conveyed with an explicit comparison to 0 or 1 or
whatever.  Saving a few keystrokes simply isn't worth the amount of time
and mental fatigue incurred when you need to debug something that's
caused by wrong interpretation of return values.


T

-- 
People tell me I'm stubborn, but I refuse to accept it!

Reply via email to