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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.