Reputation: 10126
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.
Upvotes: 0
Views: 1683
Reputation: 9884
If you find two charactes that are not equal, you increment the pointers a
and b
nevertheless and then you return *a==*b
so you return the result of comparing the characters behind the place where the strings differ. Better do it like that:
for(;*a && *b && *a==*b; a++, b++) ;
return *a==*b;
And please, please rename your function. it is evereything but strcmp.
EDIT that doesn't explain test case 4, but that's explained by the use of the function name strcmp()
as the other answers tell.
Upvotes: 1
Reputation: 4658
heres a correct strcmp
int my_strcmp(char *str1, char *str2)
{
int i;
i = 0;
while (str1[i] || str2[i])
{
if (str1[i] != str2[i])
return (str1[i] - str2[i]);
i++;
}
return (0);
}
Upvotes: 0
Reputation: 1867
I tested your code with GCC-4.4.7 and it get same result.
GCC page describes optimization for strcmp
http://gcc.gnu.org/projects/optimize.html
GCC could optimize strcmp (and memcmp) where one string is constant to compare successive bytes to known constant ones inline.
Rename your function and you will get your expected result as below:
$ cc yourcode.c
$ ./a.out
Test 1: 0
Test 2: 0
Test 3: 1
Test 4: 0
Test 5: 0
$ cc -D strcmp=strcmp1 yourcode.c
$ ./a.out
Test 1: 0
Test 2: 0
Test 3: 1
Test 4: 1
Test 5: 1
Upvotes: 2
Reputation: 20392
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.
Upvotes: 3