It is failing because your indentation is bad.
Reindented:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int cmpstr(char* s1,char* s2)
{
int result;
int i = -1;
do
{
i++;
if(*(s1+i) > *(s2+i))
result=1;
break;
if( *(s1+i) < *(s2+i) )
result=-1;
break;
if( *(s1+i) == *(s2+i) )
result = 0;
break;
} while (*(s1+i)!=0 || *(s2+i)!=0);
return result;
}
|
Notice how the
break statements do not belong to the preceding
if statement? That is your error.
Try again:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
int cmpstr(char* s1,char* s2)
{
int result;
int i = -1;
do
{
i++;
if(*(s1+i) > *(s2+i))
{
result=1;
break;
}
if( *(s1+i) < *(s2+i) )
{
result=-1;
break;
}
if( *(s1+i) == *(s2+i) )
{
result = 0;
/* break; */ /* <-- this was a mistake! */
}
} while (*(s1+i)!=0 || *(s2+i)!=0);
return result;
}
|
You could also considerably shorten it.
1 2 3 4 5 6 7 8 9 10 11
|
int cmpstr(char* s1,char* s2)
{
while (*s1 && *s2)
{
if (*s1 < *s2) return -1;
if (*s1 > *s2) return 1;
s1++;
s2++;
}
return 0;
}
|
@
Tevsky
Line 8 is valid and correct C and C++: it is called a function prototype, and is required to use the function following main(). Further, choice of
where functions are prototyped is often a matter of opinion and/or project style.
Further, since the arrays are, in fact, arrays of char, there is every reason in the book to be passing them as pointers. It is, actually, the way the C standard library is written when dealing with strings; to do similarly doesn't deserve criticism.
And again, 'initialize variables as you define' them
isn't a hard and fast rule -- albeit a good one. In this case, you might want to point out that failing to initialize the variable leaves him open to a possible nonsense result -- since any changes for every possibility inside the loop means it could terminate before
result was given value. As it is now it works...
Hope this helps.