Why is this printing out 0 back in main but 6 when it is inside of the strcmp function?
7 int main()
8 {
9 char* str = "test string";
10 char* str2 = "test strong";
11 //printf("string length = %d\n",strlen(str));
12
13 int num = strcmp(str,str2);
14
15 printf("num = %d\n",num);
16 }
29 int strcmp(char* str, char* str2)
30 {
31 if(*str == '\0' && *str2 == '\0')
32 return 0;
33 if(*str2 - *str == 0)
34 {
35 strcmp(str+1,str2+1);
36 }
37 else
38 {
39 int num = *str2 - *str;
40 cout << "num = " <<num<<endl;
41 return num;
42 }
43 }
The output is:
num = 6 num = 0
Why is it printing 0 when obviously the value that it should be returning is 6?
Did you forget to add a return
statement?
33 if(*str2 - *str == 0)
34 {
35 return strcmp(str+1,str2+1);
36 }
Otherwise, the code will just skip past the rest of your if
statement and reach the end of your function, returning nothing (or 0
in your case, but that's being lucky).
Your code will only work if the first characters of both strings are different from each other. Or if both strings are empty.
Your compiler should warn you about this; returning void
from non void
function. If not, you should compile with -Wall
:)
This is the problem:
if(*str2 - *str == 0)
{
strcmp(str+1,str2+1); /* no return here. */
}
meaning the code will drop through to end, where there is no return
, which is undefined behaviour:
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
As the behaviour is undefined anything can occur. In this case 0
is returned.
Change to:
if(*str2 - *str == 0)
{
return strcmp(str+1,str2+1);
}
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