prefix matches with C strings

  • one thing I realised while reading some code at work that worked with C strings: it’s surprising how easy it is to match a prefix on a C string.

    if (s != NULL
        && s[0] == 'h'
        && s[1] == 'u'
        && s[2] == 'g')
    {
        // ...
    }
    
    2024-11-12
  • this works because of the NUL terminator—if it appears at any point in the string, the s[i] == c comparison will return false, thus breaking the && chain—so indices always stay in-bounds!

    2024-11-12