Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does strcmp() return 0 when its inputs are equal?

Tags:

When I make a call to the C string compare function like this:

strcmp("time","time") 

It returns 0, which implies that the strings are not equal.

Can anyone tell me why C implementations seem to do this? I would think it would return a non-zero value if equal. I am curious to the reasons I am seeing this behavior.

like image 675
Xenu Avatar asked Feb 27 '09 16:02

Xenu


People also ask

Why does strcmp return to zero?

Compare Two Character Vectors Compare two different character vectors. strcmp returns 0 because s1 and s2 are not equal. Compare two equal character vectors. strcmp returns 1 because s1 and s2 are equal.

What does strcmp return if the strings are the same?

The return value from strcmp is 0 if the two strings are equal, less than 0 if str1 compares less than str2 , and greater than 0 if str1 compares greater than str2 . No other assumptions should be made about the value returned by strcmp .

Does strcmp return true or false?

The strcmp function takes two input arguments (two strings) and returns either true or false, just like any boolean expression. Strcmp will only return true if every character of both strings is the same and they are the same length.


1 Answers

strcmp returns a lexical difference (or should i call it "short-circuit serial byte comparator" ? :-) ) of the two strings you have given as parameters. 0 means that both strings are equal

A positive value means that s1 would be after s2 in a dictionary.

A negative value means that s1 would be before s2 in a dictionary.

Hence your non-zero value when comparing "time" and "money" which are obviously different, even though one would say that time is money ! :-)

like image 148
Benoît Avatar answered Sep 30 '22 10:09

Benoît