Take the 2-minute tour ×

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.


share|improve this question
Logically it should be 0, since there's no way for one of the strings to be greater or less than the other. –  Mark Ransom Jan 18 '13 at 21:29
You could always try it and see. –  ellotheth Jan 19 '13 at 0:04
add comment

1 Answer

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.

share|improve this answer
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. –  nowgains nowpains Jan 18 '13 at 21:36
@nowgainsnowpains: A string containing zero characters is identical to another string containing zero characters. –  Eric Postpischil Jan 18 '13 at 21:37
@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. –  dasblinkenlight Jan 18 '13 at 21:39
@EricPostpischil Fair explaination. Thanks. –  nowgains nowpains Jan 18 '13 at 21:40
@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. –  Daniel Fischer Jan 18 '13 at 21:40
show 2 more comments

Your Answer


