c/c++ what is the return value of strncmp when size is 0
Asked Answered
D

1

8

The c/c++ strncmp signature is like the following:

int strncmp ( const char * str1, const char * str2, size_t num );

My question is what's the return value if num is 0? How the standard says? Don't find an answer from some online documents.

Thanks.

Dealing answered 18/1, 2013 at 21:27 Comment(2)
Logically it should be 0, since there's no way for one of the strings to be greater or less than the other.Humdrum
You could always try it and see.Unpack
E
8

Well, strncmp compares at most num characters from the two strings, so with num == 0, it compares none, hence finds no difference, thus it returns 0.

Eyrir answered 18/1, 2013 at 21:29 Comment(8)
But that makes no sense. returns 0 means the two string are identical. actually there are not. If that's the standard says, then i think it is a bug in the standard. No matter what returns 0 or 1, it is not a reasonable value, I think.Dealing
@nowgainsnowpains: A string containing zero characters is identical to another string containing zero characters.Beacham
@nowgainsnowpains Although returning 0 from strcmp means that the strings are equal, this does not hold for strncmp. For that function, returning 0 means that the substrings of the first n characters are equal. Passing zero for n effectively means comparing two empty strings, which are indeed equal to each other.Megagamete
@EricPostpischil Fair explaination. Thanks.Dealing
@nowgainsnowpains strncmp compares initial parts of two strings, and returns 0, a positive value or a negative value if the prefix of length num of the first string is equal to, greater or smaller than the prefix of length num of the second string. The prefix of length 0 of any string is an empty string, so all prefixes of length 0 are equal.Eyrir
@dasblinkenlight even a more reasonable explaination. Thanks.Dealing
Another way to think of it: imagine strncmp(a, b, n), logically, as first taking strndup(a, n) and strndup(b, n) and then passing the results to strcmp.Cloakroom
@R.. I believe that both the answer and your comment are valid iff the passed pointers are != NULL otherwise the behavior is undefined, instead.Coppinger

© 2022 - 2024 — McMap. All rights reserved.