Fixing C's Biggest Mistake

Salih Dincer salihdb at hotmail.com
Wed Jan 4 16:59:06 UTC 2023


On Wednesday, 4 January 2023 at 04:24:33 UTC, areYouSureAboutThat 
wrote:
> int find (int key , @checked int a[] : len, int len ) // 
> alternative syntax using @attributes
> {
>     for (int i = 0; i < len; i ++)
>     {
>         // NOTE: a[i] is bounds checked.
>         // The checking ensures that i is between 0 and len .
>         if (a[i] == key )
>         {
>             return i;
>         }
>     }
>     return -1;
> }

I hardly ever use indexOf anymore. Because I want to not use an 
signed number. I want to be able to use it inside the if. 
Wouldn't it occur to anyone other than me to write this function:

```d
auto nextIndexOf(A)(A[] arr, A key) {
   size_t i = 1;
   while(i <= arr.length) {
     if(arr[i - 1] == key ) {
       return i;
     } else i++;
   }
   return 0;
}

void main() {
   auto fun = [ 1, 2, 3, 4, 5 ];

   import std.stdio;
   if(auto result = fun.nextIndexOf(6)) {
     "index of ".write(result - 1);
   } else {
     "Not".write;
   }
   " Found".writeln;

   if(auto result = fun.nextIndexOf(5)) {
     "index of ".write(result - 1);
   } else {
     "Not".write;
   }
}
```
Fun: "Yar bana bir eglence" by the traditional Turkish shadow 
play: Hacivat&Karagoz

SDB at 79



More information about the Digitalmars-d mailing list