Thoughts on some code breakage with 2.074
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Thu May 11 16:44:53 PDT 2017
On Thu, May 11, 2017 at 08:21:46AM -0400, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> I don't ever remember if(ptr) being deprecated. In fact, I'd go as far
> as saying that maybe H.S. Teoh misremembers the array thing as
> pointers.
>
> The biggest reason is that a huge useful pattern with this is:
>
> if(auto x = key in someAA)
> {
> // use *x without more hash lookup costs.
> }
>
> I can't imagine anyone attempted to force this to break without a loud
> backlash. I think if(ptr) is mostly universally understood to mean the
> pointer is not null.
[...]
Since the accuracy of my memory was questioned, I went back to look at
the code in question, and indeed I did misremember it, but it was not
with arrays, it was with casting pointers to bool. And it was in a
while-condition, not an if-condition. Here's a simplified version of
the original code:
struct Op {...}
Op* getOp(...) { ... }
...
Op* op;
while (!input.empty && cast(bool)(op = getOp(...))) { ... }
The cast(bool) used to be accepted up to a certain version (it was in
the code from when I first wrote it around 2012), then around 2013 it
became a compile error, which forced me to rewrite it as:
struct Op {...}
Op* getOp(...) { ... }
...
Op* op;
while (!input.empty && (op = getOp(...)) !is null) { ... }
which is much more readable and documents intent more clearly.
I originally wrote the cast(bool) because without it the compiler
rejects using assignment in an while-condition. I suppose the reasoning
is that it's too easy to mistakenly write `while (a=b)` instead of
`while (a==b)`. In modern C compilers, an extra set of parentheses
usually silenced the compiler warning about a possible typo of ==, but
in D even with parentheses the compiler would reject it.
So all things considering, this little anecdote represents the following
progression in readability (the first 2 steps are hypothetical, since
they're only permitted in C):
while (a = b) ... // in C, error-prone, could be typo
while ((a = b)) ... // still in C, marginally better
while (cast(bool)(a = b)) // early D, the conversion is now explicit
while ((a = b) !is null) // present-day D, finally intent is clear
T
--
By understanding a machine-oriented language, the programmer will tend to use a much more efficient method; it is much closer to reality. -- D. Knuth
More information about the Digitalmars-d
mailing list