length's type.

thinkunix thinkunix at zoho.com
Thu Feb 8 08:23:12 UTC 2024


Kevin Bailey via Digitalmars-d-learn wrote:
> How many times does the following loop print? I ran into this twice 
> doing the AoC exercises. It would be nice if it Just Worked.
> ```
> import std.stdio;
> 
> int main()
> {
>    char[] something = ['a', 'b', 'c'];
> 
>    for (auto i = -1; i < something.length; ++i)
>          writeln("less than");
> 
>    return 0;
> }
> ```
> 

Pretty nasty.

This seems to work but just looks bad to me.  I would never write
code like this.  It would also break if the array 'something' had
more than int.max elements.

```
import std.stdio;

int main()
{
         char[] something = ['a', 'b', 'c'];

	// len = 3, type ulong
         writeln("len: ", something.length);
         writeln("typeid(something.length): ", typeid(something.length));

         // To make the loop execute, must cast something.length
         // which is a ulong, to an int, which prevents i from
         // being promoted from int to ulong and overflowing.
         // The loop executes 4 times, when i is -1, 0, 1, and 2.
         for (auto i = -1; i < cast(int)something.length; ++i) {
                 writeln("i: ", i);
         }
         return 0;
}
```
output:

len: 3
typeid(something.length): ulong
i: -1
i: 0
i: 1
i: 2


More information about the Digitalmars-d-learn mailing list