Search code examples
cstrcmp

Can I please get some feedback for this strcmp() function I implemented in C?


I'm learning C.

I find I learn programming well when I try things and received feedback from established programmers in the language.

I decided to write my own strcmp() function, just because I thought I could :)

int strcompare(char *a, char *b) {
    while (*a == *b && *a != '\0') {
        a++;
        b++;
    }
    return *a - *b;
}

I was trying to get it to work by incrementing the pointer in the condition of the while but couldn't figure out how to do the return. I was going for the C style code, of doing as much as possible on one line :)

Can I please get some feedback from established C programmers? Can this code be improved? Do I have any bad habits?

Thanks.


Solution

    1. The function doesn't change the content of a and b. it should probably announce that by taking pointers to const strings.
    2. Most C styles are much terser than many other languages' styles, but don't try to be too clever. (In your code, with several conditions ANDed in the loop conditions, I don't think there's way to put incrementing in there, so this isn't even a question of style, but of correctness.)