Why doesn't my strcmp implementation return the correct value?

Why is this listing 0 returned to the main, but 6 when it is inside 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 }

Conclusion:

num = 6 num = 0

Why does it print 0 when, obviously, the value to be returned is 6?

+5
source share
2 answers

Have you forgot to add instructions return?

 33 if(*str2 - *str == 0)
 34   {
 35     return strcmp(str+1,str2+1);
 36   }

Otherwise, the code will simply skip the rest of your statement ifand reach the end of your function without returning anything (or 0in your case, but it was lucky).

Your code will only work if the first characters of both lines are different from each other. Or if both lines are empty.

; void non void. , -Wall:)

+8

:

if(*str2 - *str == 0)
{ 
    strcmp(str+1,str2+1); /* no return here. */
}

, , return, undefined:

  • 6.9.1 C99:

} , , undefined.

  • 6.6.3 ++ 03:

; undefined .

undefined . 0.

:

if(*str2 - *str == 0)
{ 
    return strcmp(str+1,str2+1);
}
+4

All Articles