C strncmp return 1

249 Views Asked by At

I was trying to implement my own strncmp in native C, then I started doing some tests like this one

#include <string.h>
#include <stdio.h>

printf("%d\n", strncmp("test\200", "test\0", 6));

And the return of strncmp in this particular situation was 1; can anyone explain me why?

I'm pretty sure it's because \200 exceeds default ASCII, then I implemented a condition that if the char is not between 0 and 127 I would return 1, is this right?

1

There are 1 best solutions below

0
Allan Wind On

Per man page:

int strncmp(const char *s1, const char *s2, size_t n);
...
strcmp() returns an integer indicating the result of the comparison, as follows:
• 0, if the s1 and s2 are equal;
• a negative value if s1 is less than s2;
• a positive value if s1 is greater than s2.

The numeric value is otherwise undefined.

This means \200 is greater than \0 (end of string) which more concisely would be written as:

#include <stdio.h>
#include <string.h>

int main(void) {
    printf("%d\n", strncmp("\200", "", 1));
    return 0;
}