bug in grammar with ?:
Brett
Brett at gmail.com
Tue Sep 17 18:16:41 UTC 2019
On Tuesday, 17 September 2019 at 18:06:55 UTC, ketmar wrote:
> Brett wrote:
>
>> Fails(loop is not taken):
>>
>> for(ulong i = len - 1; i >= (true) ? 0 : 1; i--)
>>
>>
>> passes
>>
>> for(ulong i = len - 1; i >= ((true) ? 0 : 1); i--)
>>
>> Only difference is parenthesis(yes, that is all, doesn't
>> matter if it's true or false)
>
> not a bug. the whole thing before `?` is a condition, so
>
> i >= (true) ? 0 : 1
>
> returns 0, of course, because `i >= 1` (your `len` is obviously
> >= 1), and the result of the expression is therefor 0.
Makes sense, seems bad though... can introduce severe bugs in
code if allowed. While using ?: there is not such a common idiom,
using >= (or <= is)
Might be better for the compiler to detect such things and give a
warning to use parenthesis? It could introduce subtle and hard to
detect bugs.
Probably 99% of for loops use the syntax of var >= ...
I use it so much that way that I always think of ... as it's own
expression rather than the entire part being an expression...
it's my fault but I imagine 95% of programmers also think along
similar ways. All it takes is forgetting this one time and one
could have serious bugs(if the condition is complex and resolves
in a hard to detect way it could produce such cases, rare but
possible).
More information about the Digitalmars-d
mailing list