Search code examples
cstrcmp

String comparison in one line


As a kind of exercise I want to implement the string comparison a short as possible. The code is below:

#include <stdio.h>

int strcmp(const char* a, const char* b)
{
     for(;a && b && *a && *b && *a++==*b++;);return *a==*b;
}


int main ()
{
    const char* s1 = "this is line";
    const char* s2 = "this is line2";
    const char* s3 = "this is";
    const char* s4 = "this is line";


    printf("Test 1: %d\n", strcmp(s1, s2));
    printf("Test 2: %d\n", strcmp(s1, s3));
    printf("Test 3: %d\n", strcmp(s1, s4));
    printf("Test 4: %d\n", strcmp(s1, s1));
    printf("Test 5: %d\n", strcmp(s2, s2));

    return 0;
}

The result is:

Test 1: 0
Test 2: 0
Test 3: 1
Test 4: 0
Test 5: 0

What is going wrong in the case of comparison of the string with itself?

NOTE: I know that there is a shorter solution, but I want to find it by myself.

EDIT: Compiler is gcc under Ubuntu.


Solution

  • Please don't call your functions the same as functions in the standard library if they don't provide the same functionality. You will break many things in subtle ways when you do that. Apparently that was the bug here.

    To add a few more useful comments here. Use a while loop instead. Don't check for arguments being NULL, that's bad style and even if the for loop ends because of that, the return statement will crash anyway because it will dereference NULL.