does strcmp always return 0, 1 (or -1) for equal, greater (or the opposite) respectively?
Printable View
does strcmp always return 0, 1 (or -1) for equal, greater (or the opposite) respectively?
Yes...
If the two strings are equal it will return 0.
If the first string is alphabetically earlier (less than) the second, it will return -1
If the first string is alphabetically later (greater than) than the second it will return 1
It may be implementation dependent...
My best suggestion is to test it with your library....
When in doubt... check it out!Code:char a[4] = "aaa";
char e[4] = "eee";
int x;
x = strcmp(a,a);
printf("%d\n",x);
x = strcmp(a,e);
printf("%d\n",x);
x = strcmp(e,a);
printf("%d\n",x);
Better read doc, coz one experiment does not mean all.
eg fflush(stdin) works with my compiler!
Quote:
The strcmp() function compares the two strings s1 and s2. It returns
an integer less than, equal to, or greater than zero if s1 is found,
respectively, to be less than, to match, or be greater than s2.
OK OK .... I give up.
The nits are all thoroughly picked.
The enemy is vanquished.
Peace and sanity will return to your valley.
GEES!
I have found that the returned value is most likely the numeric difference between the chars that were not equal. There is really no reason why a speedy program would want to convert a positive/negative value to +1 and -1 respectively when it already meets the documented criteria.
does the result depend on the compiler?
this code gave the same result on my PC (compiled with msvc & gcc)
output:Code:#include <stdio.h>
#include <string.h>
int main (void)
{
const char *str[2] = { "eeny meeny miny mo",
"function calls are so damn slow" };
printf("result: %d\n", strcmp(str[1], str[0]));
return(0);
}
Code:result: 1
It would depend on the version of the standard library used. If you're using minGW, I think you're using the same version of the standard library regardless of compiler.
EDIT: So for instance, I get -1, 0, or +1 on my windows machine regardless of whether I'm using minGW or whatever. On my Mac I get -13 for comparing "eieio" with "evil".
I said....
Tabstop says...Quote:
If the two strings are equal it will return 0.
If the first string is alphabetically earlier (less than) the second, it will return -1
If the first string is alphabetically later (greater than) than the second it will return 1
and later...Quote:
Because CommonTater is mistaken. (I feel as though I remember getting numbers larger than 1, but I don't have an example on me.)
Ain't it a pain when you get so zealous about correcting people that it comes right back around to bite you....Quote:
So for instance, I get -1, 0, or +1 on my windows machine regardless of whether I'm using minGW or whatever
http://www.open-std.org/jtc1/sc22/wg...69/n869.pdf.gzQuote:
Originally Posted by Draft C99 Standard
Regardless of whatever experiments you do with your current compiler, or whatever your local manual pages say.
Portable code use <0, ==0 and >0