diff --git a/src/system/libroot/posix/string/memcmp.c b/src/system/libroot/posix/string/memcmp.c index b6d4caaf24..1fd02c03a6 100644 --- a/src/system/libroot/posix/string/memcmp.c +++ b/src/system/libroot/posix/string/memcmp.c @@ -1,4 +1,5 @@ /* + * Copyright 2025, Haiku, Inc. All rights reserved. * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT license. */ @@ -27,11 +28,14 @@ memcmp(const void *_a, const void *_b, size_t count) b = (const unsigned char *)bsz; } - while (count-- > 0) { - int cmp = *a++ - *b++; - if (cmp != 0) - return cmp; + while (count > 0 && *a == *b) { + a++; + b++; + count--; } - return 0; + if (count == 0) + return 0; + + return *a - *b; } diff --git a/src/system/libroot/posix/string/strcmp.c b/src/system/libroot/posix/string/strcmp.c index db69903c58..38f6b191e0 100644 --- a/src/system/libroot/posix/string/strcmp.c +++ b/src/system/libroot/posix/string/strcmp.c @@ -1,4 +1,5 @@ /* + * Copyright 2025, Haiku, Inc. All rights reserved. * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT license. */ @@ -26,9 +27,10 @@ strcmp(char const *a, char const *b) b = (const char *)b32; } - while (1) { - int cmp = (unsigned char)*a - (unsigned char)*b++; - if (cmp != 0 || *a++ == '\0') - return cmp; + while (*a == *b && *a != 0) { + a++; + b++; } + + return (unsigned char)*a - (unsigned char)*b; } diff --git a/src/system/libroot/posix/string/strncmp.c b/src/system/libroot/posix/string/strncmp.c index dcfadda677..665a00d36e 100644 --- a/src/system/libroot/posix/string/strncmp.c +++ b/src/system/libroot/posix/string/strncmp.c @@ -1,4 +1,5 @@ /* + * Copyright 2025, Haiku, Inc. All rights reserved. * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT license. */ @@ -27,11 +28,14 @@ strncmp(char const *a, char const *b, size_t count) b = (const char *)b32; } - while (count-- > 0) { - int cmp = (unsigned char)*a - (unsigned char)*b++; - if (cmp != 0 || *a++ == '\0') - return cmp; + while (count > 0 && *a == *b && *a != 0) { + a++; + b++; + count--; } - return 0; + if (count == 0) + return 0; + + return (unsigned char)*a - (unsigned char)*b; }