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.
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.
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 .
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.
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 ! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With