logoalt Hacker News

throwaway2037 • today at 6:00 AM • 0 replies • view on HN

His final solution is so tricky. I needed to re-read it a few times to understand the trick of using post decrement in the for loop condition. Personally, I would never write code like that. I would always find a way to use ssize_t.

This part was an interesting requirement:

    > ssize_t is a POSIX thing so you'd have to define it yourself on windows.
That seems like a lot of mental gymnastics to avoid this very simple macro:

    > #if defined(_WIN32) && !defined(ssize_t)
    > #define ssize_t SSIZE_T
    > #endif
Read about the Win32 macro SSIZE_T here: https://learn.microsoft.com/en-us/windows/win32/winprog/wind...

To me, this solution is more readable and maintainable:

    > for (ssize_t i = count - 1; i >= 0; i--)
    > {
    >     if (haystack[i] == needle)
    >     {
    >         *where = i;
    >         return 1;
    >     }
    > }
    > return 0;
Alternatively, you can use a while loop where the condition appears at the end of the loop:

    > size_t i = count - 1;
    > while (1)  // true
    > {
    >     if (haystack[i] == needle)
    >     {
    >         *where = i;
    >         return 1;
    >     }
    >     if (0 == i)
    >     {
    >         return 0;
    >     }
    >     --i;
    > }