If you want better performance, you should be using the standard library function strcmp()
:
#include <string.h>
int str_unequal(const char *str1, const char *str2)
{
return strcmp(str1, str2) != 0;
}
The library function can take advantage of the target processor, possibly comparing multiple characters per iteration, which you can't easily do in a portable C program.
Other issues in the function:
strequal()
is a name reserved for future library extension, as is any identifier beginning str
followed immediately by a letter.
equal
is misleading in the name, as it returns true only when the strings are unequal.
while (1)
is dubious practice, especially given that there's a natural terminating condition (end of one of the strings).
- Unnecessary parentheses around the result of dereference operator
*
- that's higher precedence than comparisons.
- The final
return 0;
is unreachable.
Problems with the test program:
- Uses
printf
without including <stdio.h>
.
- Should explicitly state that
main()
accepts no arguments (i.e. int main(void)
).
- Only tests a small portion of the functionality (no tests of two equal strings, or one that's a prefix of the other).
- Always returns a success status, even when the function is wrong.
Modified function and tests:
int str_equal(const char *s1, const char *s2)
{
while (*s1) {
if (*s1++ != *s2++) {
return 0;
}
}
return !*s2;
}
#include <stdio.h>
int test_str_equal(int expected, const char *a, const char *b)
{
int actual = str_equal(a, b);
if (actual == expected) { return 0; }
fprintf(stderr, "\"%s\"==\"%s\" should return %d\n", a, b, expected);
return 1;
}
int main(void)
{
return test_str_equal(1, "", "")
+ test_str_equal(0, "", "x")
+ test_str_equal(0, "x", "")
+ test_str_equal(1, "x", "x")
+ test_str_equal(0, "x", "y")
+ test_str_equal(0, "x", "xy")
+ test_str_equal(0, "xy", "x")
+ test_str_equal(0, "xx", "xy")
+ test_str_equal(1, "xy", "xy");
}