Idiomatic D code to avoid or detect devision by zero

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 3 14:50:36 UTC 2020


On 8/3/20 5:53 AM, Martin Tschierschke wrote:
> On Friday, 31 July 2020 at 14:18:15 UTC, Steven Schveighoffer wrote:
>> On 7/31/20 9:55 AM, Martin Tschierschke wrote:
>>> What would be the idiomatic way to write a floating point division
>>> occuring inside a loop and handle the case of division by zero.
>>>
>>> c = a/b; // b might be zero sometimes, than set c to an other value (d).
>>>
>>> (In the moment I check the divisor being zero or not, with an 
>>> if-than-else structure,
>>> but I find it ugly and so I ask here.)
>>
>> c = b == 0 ? d : a/b;
>>
>> I don't think a function would be shorter or clearer...
>>
>> c = div(a, b, d);
>>
>> Alternatively, you could use a type to effect the behavior you want.
>>
> 
> Thanks, for the hints.
> I find the ? :  - expressions sometimes hard to reed, especially when a 
> and b are not so  simple expressions.
> 
> I prefer putting additional bracket around:
> c = (b_expression == 0) ? (d_longer_expression) : 
> (a_expression/b_expression);

Yes, that is fine, and up to your preference. You may actually need the 
parentheses if the expressions somehow override the precedence of the ?: 
operator.

Even with symbol uses, I personally would do actually:

c = (b == 0 ? d : a/b);

Just because the ` = b == ` looks really bad to me.

-Steve


More information about the Digitalmars-d-learn mailing list