Strange behavior of iota

bachmeier no at spam.net
Wed Feb 16 14:06:00 UTC 2022


On Wednesday, 16 February 2022 at 02:51:32 UTC, Era Scarecrow 
wrote:
> On Tuesday, 15 February 2022 at 22:24:53 UTC, bachmeier wrote:
>> On Tuesday, 15 February 2022 at 22:02:13 UTC, Adam D Ruppe 
>> wrote:
>>> for(a = v.length; a > cast(size_t) -1, a += -1)
>>
>> After looking at the documentation and seeing CommonType!(int, 
>> uint) is uint, I have to say that iota's behavior doesn't make 
>> much sense.
>
> Unless it's almost always intended to go up and stay positive?

That may have been the intended use case, but it's poor design to 
not enforce it. I was using it to iterate through the indexes on 
an array backwards. You have to set the second argument to -1 to 
get the last index to be 0.

On a larger scale, it's D's principle that it's okay to throw 
unsigned types around and leave it to the programmer to hang 
themself. It's hard to see how anyone could think it makes sense 
to silently convert -1 to 18446744073709551615 without even a 
warning.

This compiles:

```
void main() {
     void foo(int x) {}
     void bar(uint x) {}

     bar(-1.to!uint);
}
```

This doesn't:

```
void main() {
     void foo(int x) {}
     void bar(uint x) {}

     foo(-1.to!long);
}
```


More information about the Digitalmars-d-learn mailing list