Providing implicit conversion of - memory-safety
Renato
renato at athaydes.com
Wed Jan 24 07:34:05 UTC 2024
On Tuesday, 23 January 2024 at 23:40:55 UTC, Danilo wrote:
> How did you make it correct?
>
> Write 2 different versions for `signed` and `unsigned` types?
> Or could you utilize `core.checkedint` somehow for checking
> overflow?
>
> ```d
> double value(T)(T index, double * x) {
> bool overflow;
> subu(index, 5, overflow);
>
> if (overflow) {
> return 0.0;
> } else {
> return x[index-5];
> }
> }
> ```
> This is probably only correct for `unsigned` types.
When you have a variable with a "potentially" unsigned type, you
must not subtract from it unless you're sure the result is not
going negative. The fixed code only subtracts 5 from `index`
after checking that `index >= 5`, so it is always safe.
Your previous code was trying to do the same thing incorrectly
because it just subtracted 5 **first**. This is analogous to
checking pointers for null before using them.
The type parameter restriction was not necessary, but it was
added because the code is assuming that the type can be coerced
to size_t, as it's being used as an index - so it's a good idea
to make that part of the template's "signature"... even without
the type limitation, your code wouldn't compile if this was not
the case (but your error message will probably be much worse).
More information about the Digitalmars-d-learn
mailing list