Search code examples
c++stringcharstrcmp

strcmp confusion


To my knowledge the standard strcmp function looks something like this:

int strcmp(const char* string1, const char* string2)
{
    while(*pString1++ == *pString2++)
    {
        if(*pString1 == 0) return 0;
    }
    return *pString1 - pString2;
}

My question is that wouldn't this increment the pointers passed into strcmp? In the following example it seems like it would trash the pointers and cause invalid stuff to happen.

const char* string1 = "blah";
const char* string2 = "blah";
const char* string3 = "blah";
if(strcmp(string1, string2) {doSomething();} 
// Won't this make string1 = "" because it incremented the pointer to the end?
else if (strcmp(string1, string3) {doSomethingElse();}

Sorry I'm just confused because it seems like if I pass a pointer into strcmp, I shouldn't expect that pointer to suddenly hold an empty string. It seems like strcmp should take const char* const. Am I totally misunderstanding something?


Solution

  • Your misunderstanding is this: Arguments are passed by value (copy), but you seem to think they are passed by reference.

    You could get your expected behaviour by declaring the parameters to strcmp as references, like this:

    int strcmp(const char*& string1, const char*& string2)