Jump to content

strpos returning false is not buggy?


johnmerlino1

Recommended Posts

I find it a bit buggy that strpos returns false instead of -1.

 

The equivalent C implementation returns -1:

int strpos(char s[], char t[])
{
    int i, j, k;

    for (i = 0; s[i] != '\0'; i++) {
        for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
            ;

        if (k > 0 && t[k] == '\0')
            return i;
    }

    return -1;
}

The problem with returning false is that false can also evaluate to 0 which can also happen to be the first index of a match. Therefore, you have a hard to find bug. I know that you can use the identity operator to check for falseness: ===. But wouldn't it be a better design for the function to just return -1?

Link to comment
https://forums.phpfreaks.com/topic/290144-strpos-returning-false-is-not-buggy/
Share on other sites

C returns -1 because it can't return a mixed boolean/integer (putting aside the fact that it doesn't have actual booleans in the first place). PHP can so it returns false.

 

Frankly I'd rather it returns false: I see false == 0 being a better situation than -1 == true.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.