Understanding strcmp implementation in 'C'

The below function is from the link:

http://clc-wiki.net/wiki/C_standard_library:string.h:strcmp

It's the strcmp implementation in 'C' and i am guessing the same implementation is passed onto C++.

Can anybody explain what is going on in the last line of code. I see that the return type of the function is 'int' so the code is somehow converting pointer to int but i don't understand how?

1
2
3
4
5
6
7

int strcmp(const char* s1, const char* s2)
{
    while(*s1 && (*s1==*s2))
        s1++,s2++;
    return *(const unsigned char*)s1-*(const unsigned char*)s2;
}


Regards
Saher ch
That function is not converting a pointer to an int, it is converting characters to an int. Specifically the characters pointed to by *s1 and *s2.

If the strings are "HEllo" and "Hello" it would be returning 'E' (69) - 'e' (101) or -32.

*(const unsigned char*)s1
The (const unsigned char*)s1 part basically means
static_cast<const unsigned char*>(s1)
So we have pointer to const unsigned char. You also see that before (const unsigned char*)s1 there is one more * what means that we are dereferencing this pointer and getting just const unsigned char what was pointed to by this pointer

Same thing happens with s2 and now we have just 2 const unsigned chars.
You can implicitly convert the difference between s1 and s2 what is const unsigned char to int


EDIT : correct me if im wrong maybe
(const unsigned char*)s1
means
reinterpret_cast<const unsigned char*>(s1)
instead of
static_cast<const unsigned char*>(s1)
Last edited on
Remember, char is an integer type, so they can treated just like any other integer. Their only special quality is that they display differently than other kinds of integer.

Subtracting the two provides a negative value (s1 < s2), a positive value (s1 > s2), or zero (s1 == s2).

@etrusks
Neither; a c-style cast is an absolute, I'm smarter than the compiler, cast.
Thanks man! =]
Topic archived. No new replies allowed.