January 11th, 2013, 11:06 AM
Strcmp() returns wrong value
here's the code for example:
here's the output:
char str1, str2;
printf("Enter first string:");
printf("Enter second string:");
what's wrong with it?
Enter first string: hello
Enter second string: world
why wouldn't it return 1 as it should?
January 11th, 2013, 11:56 AM
Why would you expect it to return 1?
The spec for strcmp reads
<0 if a is before b
>0 if a is after b
== 0 if they're the same
You have -15, indicating "hello" is before "world" (which it is).
January 12th, 2013, 04:27 AM
for some reason (maybe i read it somwhere) i thought that if it reurns 1 then first string is before second string, 0 if they're the same, and -1 if second string is before the first string...
January 13th, 2013, 12:00 AM
Some languages have a comparison function like strcmp but specifically return -1, 0, or 1. The C function returns the difference between the two strings (as you may have realized) and thus merely guarantees a negative, zero, or positive number.
As for returning 1/positive if the first string < second string, I'm not sure where you got that from. No offense but you might just be remembering it backwards.
January 13th, 2013, 03:25 AM
Reading it somewhere is good; but perhaps you should have checked before posting a question. There are many sources for documentation of teh standard library; here's one. If the documentation only guarantees <0, 0, or >0, even if you observe -1, 0 and 1 in any particular implementation, you cannot assume that that will always be the case.
Originally Posted by so.very.tired
In this case -15 is the result of performing 'w' - 'h' which gives a clue as to how strcmp() is working in this case. It is simply performing a numerical comparison of the character codes, and returns the difference between the first two non-matching characters.